Masking an image in RecyclerView programmatically - java

I have my main layout display listings via RecyclerView. I want it to look something like this:
Expected layout
I'm using simple, square .jpg pictures and I want to apply a consistent mask across all listings (a single object, codewise).
There are a few answers out there for making masks but I can't seem to apply those to my needs,
as all or most of them are referring to a simple layout or a single ImageView, but how should it work in my case? Code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#color/colorPrimaryLight"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/tb"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingTop="25dp"
android:soundEffectsEnabled="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tb" />
<com.google.android.material.navigation.NavigationView
android:layout_width="50dp"
android:layout_height="16dp"
app:layout_constraintBottom_toBottomOf="#id/tb"
app:layout_constraintEnd_toEndOf="#id/tb"
app:layout_constraintHorizontal_bias="0.083"
app:layout_constraintStart_toStartOf="#id/tb"
app:layout_constraintTop_toTopOf="#id/tb"
app:layout_constraintVertical_bias="0.4" />
</androidx.constraintlayout.widget.ConstraintLayout>
item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
style="#android:style/Widget.Material.Button.Borderless"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="124dp"
android:layout_height="130dp"
android:contentDescription="#string/descriptor"
app:layout_constraintBottom_toBottomOf="#id/btn_read_more"
app:layout_constraintEnd_toEndOf="#id/btn_read_more"
app:layout_constraintHorizontal_bias="0.947"
app:layout_constraintStart_toStartOf="#id/btn_read_more"
app:layout_constraintTop_toTopOf="#id/btn_read_more"
app:layout_constraintVertical_bias="0.421"
app:srcCompat="#mipmap/ic_launcher_round" />
<TextView
android:id="#+id/textTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/descriptor"
android:textColor="#color/text_color"
android:textDirection="rtl"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#id/textBody"
app:layout_constraintEnd_toStartOf="#id/imageView"
app:layout_constraintHorizontal_bias="0.979"
app:layout_constraintStart_toStartOf="#id/btn_read_more"
app:layout_constraintTop_toTopOf="#id/btn_read_more" />
<TextView
android:id="#+id/textBody"
android:layout_width="268dp"
android:layout_height="90dp"
android:text="#string/descriptor"
android:textColor="#color/text_color"
android:textDirection="rtl"
android:textSize="14sp"
app:layout_constraintBottom_toBottomOf="#id/btn_read_more"
app:layout_constraintTop_toBottomOf="#id/textTitle"
app:layout_constraintStart_toStartOf="#id/btn_read_more"
app:layout_constraintEnd_toStartOf="#id/imageView"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="45dp" />
<Button
android:id="#+id/btn_read_more"
android:layout_width="408dp"
android:layout_height="149dp"
android:layout_marginStart="2dp"
android:layout_marginTop="2dp"
android:layout_marginEnd="1dp"
android:background="#00FAFAFA"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.mytrip;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import android.view.Menu;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
#Override
// show the settings overflow menu
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setting the a tool bar as an action bar
Toolbar action_bar = (Toolbar) findViewById(R.id.tb);
setSupportActionBar(action_bar);
recyclerView = findViewById(R.id.rv);
// setting a linear layout (vertical) for the recycle view
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
// filling the array list
List<ModelClass> modelClassList = new ArrayList<>();
modelClassList.add(new ModelClass(R.drawable.shofet_pic, getString(R.string.shofet_title),
this.getResources().getString(R.string.shofet_desc).substring(0,75) + "..."));
modelClassList.add(new ModelClass(R.drawable.dor_pic, getString(R.string.dor_title),
this.getResources().getString(R.string.dor_desc).substring(0,75) + "..."));
modelClassList.add(new ModelClass(R.drawable.sorek_pic, getString(R.string.sorek_title),
this.getResources().getString(R.string.sorek_desc).substring(0,75) + "..."));
modelClassList.add(new ModelClass(R.drawable.red_pic, getString(R.string.red_title),
this.getResources().getString(R.string.red_desc).substring(0,75) + "..."));
modelClassList.add(new ModelClass(R.drawable.ayun_pic, getString(R.string.ayun_title),
this.getResources().getString(R.string.ayun_desc).substring(0,75) + "..."));
modelClassList.add(new ModelClass(R.drawable.gedi_pic, getString(R.string.gedi_title),
this.getResources().getString(R.string.gedi_desc).substring(0,75) + "..."));
modelClassList.add(new ModelClass(R.drawable.ofir_pic, getString(R.string.ofir_title),
this.getResources().getString(R.string.ofir_desc).substring(0,75) + "..."));
modelClassList.add(new ModelClass(R.drawable.sharon_pic, getString(R.string.sharon_title),
this.getResources().getString(R.string.sharon_desc).substring(0,75) + "..."));
modelClassList.add(new ModelClass(R.drawable.meron_pic, getString(R.string.meron_title),
this.getResources().getString(R.string.meron_desc).substring(0,75) + "..."));
modelClassList.add(new ModelClass(R.drawable.snir_pic, getString(R.string.snir_title),
this.getResources().getString(R.string.snir_desc).substring(0,75) + "..."));
modelClassList.add(new ModelClass(R.drawable.cave_pic,getString(R.string.cave_title),
this.getResources().getString(R.string.cave_desc).substring(0,75) + "..."));
// using the adapter class
Adapter adapter = new Adapter(modelClassList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
Adapter.java
package com.example.mytrip;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.Viewholder> {
private List<ModelClass> modelClassList;
public Adapter(List<ModelClass> modelClassList) {
this.modelClassList = modelClassList;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,
viewGroup, false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull final Viewholder viewholder, final int position) {
final int resource = modelClassList.get(position).getImageIcon();
final String title = modelClassList.get(position).getTitle();
final String body = modelClassList.get(position).getBody();
viewholder.btnReadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), AllTripInfo.class);
intent.putExtra("tripId", position);
v.getContext().startActivity(intent);
}
});
viewholder.setData(resource, title, body);
}
#Override
public int getItemCount() {
return modelClassList.size();
}
static class Viewholder extends RecyclerView.ViewHolder{
private ImageView imageView;
private TextView title;
private TextView body;
Button btnReadMore;
public Viewholder(#NonNull View itemView) {
super(itemView);
btnReadMore = itemView.findViewById(R.id.btn_read_more);
imageView = itemView.findViewById(R.id.imageView);
title = itemView.findViewById(R.id.textTitle);
body = itemView.findViewById(R.id.textBody);
}
private void setData(int imageResource, String titleText, String bodyText)
{
imageView.setImageResource(imageResource);
title.setText(titleText);
body.setText(bodyText);
}
}
}
ModelClass.java
package com.example.mytrip;
public class ModelClass {
private int imageIcon;
String title;
String body;
public ModelClass(int imageIcon, String title, String body) {
this.imageIcon = imageIcon;
this.title = title;
this.body = body;
}
public int getImageIcon() {
return imageIcon;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
}
For answer's sake, I want a circular mask, whether programmatically or even a white .png extracted via Photoshop.
Any further tips for optimizing my code in any way are welcome as well. I will definitely have to do something about the fact that the listings are not clickable themselves, but rather have a big transparent button on top...
Thank you!

Ronny Just Change in your Item_layout.
Just Add the circularImage library in your app-level gradle file.
CircleImageView
your item layout will look like:
<RelativeLayout>
<Text></Text>
<de.hdodenhof.circleimageview.CircleImageView>
//add endParent= true
</de.hdodenhof.circleimageview.CircleImageView>
</RelativeLayout>

Related

RecyclerView is not showing in Activity

I have a NewsDetailsActivity file that is displaying some news details. On top of the news details I want to display some cardview in a recyclerview. The recyclerView is not showing up but the worse part is that another recyclerview (that I have in the MainActivity is showing up in my NewsDetailsActivity like if If I am calling some id from my NewsDetailsActivity.
The only thing I want is to display some information on the top of the news details using the the recyclerview id my_recycler_view_coin_details
NewsDetailsActivity
package com.noticripto.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.noticripto.APIClientCoin;
import com.noticripto.adapters.CryptoListAdapter;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.noticripto.MainActivity;
import com.noticripto.R;
import com.noticripto.adapters.NewsAdapter;
import com.noticripto.model.HomePageModel;
import com.noticripto.rest.ApiClient;
import com.noticripto.rest.ApiInterface;
import com.noticripto.retrofit.CryptoList;
import com.noticripto.retrofit.Datum;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class NewsDetailActivity extends AppCompatActivity {
Toolbar toolbar;
TextView sourceName, newsTitle, newsDesc, newsDate, newsView,labelSimilar;
Button viewMore;
ImageView imagy,small_icn;
ProgressBar progressBar;
RecyclerView recyclerView3;
CryptoListAdapter adapterCoin2;
ApiInterface apiInterfaceCoin2;
List<Datum> cryptoList2 = null;
HomePageModel.News detailNews = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_detail);
apiInterfaceCoin2 = APIClientCoin.getClient().create(ApiInterface.class);
recyclerView3 = findViewById(R.id.my_recycler_view_coin_details);
initViews();
LoadNewsDetails();
getCoinList();
}
private void LoadNewsDetails() {
// Calling our api
ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Map<String, String> params = new HashMap<>();
params.put("id" , getIntent().getIntExtra("pid", 0) + "");
Call<HomePageModel> call = apiInterface.getNewsDetailsById(params);
call.enqueue(new Callback<HomePageModel>() {
#Override
public void onResponse(Call<HomePageModel> call, Response<HomePageModel> response) {
// Update the news layout
detailNews = response.body().getNews().get(0);
newsTitle.setText(detailNews.getTitle());
newsDesc.setText(NewsAdapter.removeHtml(detailNews.getPostContent()));
if (detailNews.getImage().length() >=1){
Glide.with(NewsDetailActivity.this)
.load(detailNews.getImage())
.placeholder(R.drawable.image1)
.into(imagy);
}else{
imagy.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<HomePageModel> call, Throwable t) {
progressBar.setVisibility(View.GONE);
}
});
}
private void initViews() {
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
toolbar.setNavigationIcon(R.drawable.icon_arrow_back_white);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
cryptoList2 = new ArrayList<>();
adapterCoin2 = new CryptoListAdapter(cryptoList2);
// sourceName = findViewById(R.id.source_name );
newsTitle = findViewById(R.id.news_title);
newsDesc = findViewById(R.id.news_desc);
newsDate = findViewById(R.id.news_date);
//newsView = findViewById(R.id.news_view);
labelSimilar = findViewById(R.id.label_similar_news);
//viewMore = findViewById(R.id.view_more);
progressBar = findViewById(R.id.progressBar);
imagy =findViewById(R.id.news_image);
//small_icn = findViewById(R.id.small_icn);
recyclerView3 = findViewById(R.id.my_recycler_view_coin_details);
LinearLayoutManager linearLayoutManager3 =new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView3.setLayoutManager(linearLayoutManager3);
recyclerView3.setNestedScrollingEnabled(false);
recyclerView3.setAdapter(adapterCoin2);
adapterCoin2.notifyItemInserted(0);
recyclerView3.scrollToPosition(0);
}
public void getCoinList() {
Call<CryptoList> call2 = apiInterfaceCoin2.doGetUserList("20");
call2.enqueue(new Callback<CryptoList>() {
#Override
public void onResponse(Call<CryptoList> call, Response<CryptoList> response)
{
CryptoList list = response.body();
cryptoList2.clear();
cryptoList2.addAll(list.getData());
adapterCoin2.notifyDataSetChanged();
System.out.println("List getData = " + list.getData());
}
#Override
public void onFailure(Call<CryptoList> call, Throwable t) {
Toast.makeText(NewsDetailActivity.this, "onFailure",
Toast.LENGTH_SHORT).show();
Log.d("XXXX", t.getLocalizedMessage());
call.cancel();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.news_details_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.share){
if (detailNews != null){
// Opening sharing options
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, detailNews.getTitle());
i.putExtra(Intent.EXTRA_TEXT, detailNews.getPostContent());
startActivity(i);
}else{
Toast.makeText(this, "Lo Sentimos!", Toast.LENGTH_SHORT).show();
}
}
return super.onOptionsItemSelected(item);
}
}
crypto_list_item_in_detail_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardViewCoinDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
app:cardCornerRadius="8dp"
app:cardBackgroundColor="#android:color/white">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/symbolNameDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="roboto_bold"
android:gravity="center"
android:paddingBottom="3dp"
android:singleLine="true"
android:text="Symbol"
android:textAppearance="#android:style/TextAppearance.Large"
android:textColor="#000"
android:textSize="15dp" />
<TextView
android:id="#+id/priceDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textStyle="bold"
android:text="Price"
android:textSize="13dp"
android:layout_marginBottom="5dp"
android:layout_toRightOf="#+id/symbolNameDetails"
android:textAppearance="#android:style/TextAppearance.Medium"
android:textColor="#000" />
</RelativeLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
activity_news_details.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.NewsDetailActivity">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbar"
android:background="#color/black"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_below="#+id/toolbar"
android:layout_height="wrap_content">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:indeterminateTint="#color/yellow"/>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
android:overScrollMode="never"
android:layout_below="#+id/progressBar">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/my_recycler_view_coin_details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="horizontal" />
<androidx.cardview.widget.CardView
android:id="#+id/wrapper_cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/wrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/news_title"
android:text="Titulo"
android:textStyle="bold"
android:layout_below="#+id/wrapper"
android:textSize="22sp"
android:paddingLeft="16dp"
android:textAlignment="center"
android:paddingStart="16dp"
android:textColor="#color/black"
android:gravity="center_horizontal" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/wrapper_news"
android:layout_below="#id/news_title"
android:paddingLeft="10dp"
android:layout_marginTop="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/news_date"
android:paddingEnd="10dp"
android:paddingStart="10dp"
android:text="Date"
android:paddingRight="5dp"/>
</RelativeLayout>
<ImageView
android:layout_width="match_parent"
android:adjustViewBounds="true"
android:id="#+id/news_image"
android:src="#drawable/icon_youtube"
android:layout_below="#id/wrapper_news"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/news_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/news_image"
android:fontFamily="#font/roboto"
android:padding="10dp"
android:text="News Description"
android:firstBaselineToTopHeight="0dp"
android:includeFontPadding="false"
android:lineSpacingExtra="2dp"
android:textColor="#color/black"
android:textSize="17sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/wrapper_cardview"
android:padding="10dp"
android:textSize="18sp"
android:text="Similar News"
android:visibility="gone"
android:id="#+id/label_similar_news"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/news_recy"
android:layout_below="#id/label_similar_news"/>
</RelativeLayout>
</androidx.core.widget.NestedScrollView>
</RelativeLayout>
</RelativeLayout>
And finally, I am trying to get the list from here:
CryptoListAdapter
package com.noticripto.adapters;
import android.content.Context;
import android.graphics.Color;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.noticripto.retrofit.Datum;
import com.noticripto.R;
import java.util.List;
public class CryptoListAdapter extends
RecyclerView.Adapter<CryptoListAdapter.ViewHolder> {
private List<Datum> mData;
private ItemClickListener mClickListener;
ImageView arrowImage;
RelativeLayout layout;
RelativeLayout symbolBG;
// data is passed into the constructor
public CryptoListAdapter(List<Datum> data) {
this.mData = data;
}
// Usually involves inflating a layout from XML and returning the holder
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.crypto_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
layout = view.findViewById(R.id.relativeBG);
symbolBG = view.findViewById(R.id.symbolBG);
arrowImage = view.findViewById(R.id.arrow_img);
return viewHolder;
}
// Involves populating data into the item through holder
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Get the data model based on position
Datum datum = mData.get(position);
TextView symbolName = holder.symbolName;
symbolName.setText(" (" + datum.getSymbol() + ")");
// Set item views based on your views and data model
TextView name = holder.name;
name.setText(datum.getName());
TextView symbolNameDetails = holder.symbolNameDetails;
symbolNameDetails.setText(datum.getSymbol());
TextView price = holder.price;
TextView priceDetails = holder.priceDetails;
if(datum.getQuote().getUSD().getPrice() >= 1) {
price.setText("$" + String.format("%.2f", datum.getQuote().getUSD().getPrice()));
priceDetails.setText("$" + String.format("%.2f", datum.getQuote().getUSD().getPrice()));
}else{
price.setText("$" + String.format("%f", datum.getQuote().getUSD().getPrice()));
priceDetails.setText("$" + String.format("%.2f", datum.getQuote().getUSD().getPrice()));
}
//TextView marketCap = holder.marketCap;
//marketCap.setText("Market Cap: $" + String.format("%,d",
Math.round(datum.getQuote().getUSD().getMarketCap())));
//TextView volume24h = holder.volume24h;
//volume24h.setText("Volume/24h: $" + String.format("%,d",
Math.round(datum.getQuote().getUSD().getVolume24h())));
//TextView textView1h = holder.textView1h;
//textView1h.setText(String.format("1h: %.2f",
datum.getQuote().getUSD().getPercentChange1h()) + "%");
TextView textView24h = holder.textView24h;
textView24h.setText(String.format("%.2f", datum.getQuote().getUSD().getPercentChange24h()) + "%");
if(datum.getQuote().getUSD().getPercentChange24h() < 0.0){
//red
textView24h.setText(String.format("%.2f", Math.abs(datum.getQuote().getUSD().getPercentChange24h())) + "%");
textView24h.setTextColor(Color.parseColor("#ffffff"));
arrowImage.setImageResource(R.drawable.arrow_down_white);
layout.setBackgroundColor(Color.parseColor("#EA3943"));
symbolBG.setBackgroundColor(Color.parseColor("#EA3943"));
priceDetails.setTextColor(Color.parseColor("#EA3943"));
}else{
//green
textView24h.setText(String.format("%.2f",
Math.abs(datum.getQuote().getUSD().getPercentChange24h())) + "%");
textView24h.setTextColor(Color.parseColor("#ffffff"));
arrowImage.setImageResource(R.drawable.arrow_up_white);
layout.setBackgroundColor(Color.parseColor("#18C784"));
symbolBG.setBackgroundColor(Color.parseColor("#18C784"));
priceDetails.setTextColor(Color.parseColor("#18C784"));
}
//TextView textView7d = holder.textView7d;
//textView7d.setText(String.format("7d: %.2f",
datum.getQuote().getUSD().getPercentChange7d()) + "%");
}
// Returns the total count of items in the list
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
// Your holder should contain a member variable
// for any view that will be set as you render a row
TextView name;
TextView price;
TextView marketCap;
TextView volume24h;
TextView textView1h;
TextView textView24h;
TextView textView7d;
TextView symbolName;
TextView priceDetails;
TextView symbolNameDetails;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
ViewHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
name = itemView.findViewById(R.id.name);
price = itemView.findViewById(R.id.price);
//marketCap = itemView.findViewById(R.id.marketCap);
// volume24h = itemView.findViewById(R.id.volume24h);
//textView1h = itemView.findViewById(R.id.textView1h);
textView24h = itemView.findViewById(R.id.textView24h);
//textView7d = itemView.findViewById(R.id.textView7d);
symbolName = itemView.findViewById(R.id.symbolName);
priceDetails = itemView.findViewById(R.id.priceDetails);
symbolNameDetails = itemView.findViewById(R.id.symbolNameDetails);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view,
getAdapterPosition());
}
}
// convenience method for getting data at click position
public Datum getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
The log doesn't say anything helpful just that the list might be empty but the same list is working on the MainActivity so, I believe the problem is inside my NewsDetailActivity.
I also tried some of the answers and none of them helped me:
RecyclerView is not showing
RecyclerView is not showing items
CardView is not showing properly in RecyclerView
Again, i just want to display my list from CryptoListAdapter under the NewsDetailActivity toolbar...in a nice cardview
This is what I want to do...
this is simple and normal! you fill your array in getCoinList() but set adapter for RecyclerView in initViews() in this way your array not filled yet but you pass it to your recycler! , you should get your array first , then pass it to adapter and set adapter to RecyclerView.

Showing xml for correct view

When a user logs in to my app, they can either click the view students button or daily grading button. The view students will display a student's image and their name. The daily grading will display the student's image, name, and two checkboxes that says pass or fail. Now the issue I have is that the checkboxes for pass and fail are showing up in my activity_view_students.xml view when it should not be. It should only show when a user clicks daily grading. I will put images below to make it clearer
What it looks like in the activity_view_students.xml
What it should look like in activity_view_students.xml
I will paste all relevant code below.
ViewStudents.java
package com.example.studenttracker;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ViewStudents extends AppCompatActivity {
RecyclerView recyclerView;
Button addStudent;
private DatabaseReference myRef;
public ArrayList<Students> students;
private RecyclerAdapter recyclerAdapter;
private Button orderStudents;
private EditText mEditTextAge;
private EditText mEditTextAssignment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_students);
recyclerView = findViewById(R.id.recyclerView);
addStudent = findViewById(R.id.addStudentButton);
mEditTextAge = findViewById(R.id.EditTextAge);
mEditTextAssignment = findViewById(R.id.EditTextAssignment);
orderStudents = findViewById(R.id.orderStudents);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ViewStudents.this, AddStudent.class));
}
});
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setHasFixedSize(true);
myRef = FirebaseDatabase.getInstance().getReference();
students = new ArrayList<>();
ClearAll();
GetDataFromFirebase();
}
private void GetDataFromFirebase() {
Query query = myRef.child("student");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
Students student = new Students();
if (snapshot.child("url").getValue() == null) {
student.setImageUrl(snapshot.child("imageUrl").getValue().toString());
}
else {
student.setImageUrl(snapshot.child("url").getValue().toString());
}
// student.setAge(mEditTextAge.getText().toString());
// student.setAssignment(mEditTextAssignment.getText().toString().trim());
student.setName(snapshot.child("name").getValue().toString());
students.add(student);
}
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), students);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void ClearAll() {
if (students != null) {
students.clear();
if(recyclerAdapter != null) {
recyclerAdapter.notifyDataSetChanged();
}
}
students = new ArrayList<>();
}
public void orderStudents(View view) {
Collections.sort( students, new Comparator<Students>() {
#Override
public int compare( Students o1, Students o2 ) {
return o1.name.compareTo( o2.name );
}
});
recyclerAdapter.notifyDataSetChanged();
}
}
RecyclerAdapter.java
package com.example.studenttracker;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Students> studentsArrayList;
public RecyclerAdapter(Context mContext, ArrayList<Students> studentsArrayList) {
this.mContext = mContext;
this.studentsArrayList = studentsArrayList;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_student_item,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//TextView
holder.textView.setText(studentsArrayList.get(position).getName());
Glide.with(mContext).load(studentsArrayList.get(position).getImageUrl()).into(holder.imageView);
// if (studentsArrayList.get(position).get) { //check if you need the buttons or not
// holder..setVisibility(View.VISIBLE);
// holder.checkBox2.setVisibility(View.VISIBLE);
// } else {
// holder.checkBox.setVisibility(View.GONE);
// holder.checkBox2.setVisibility(View.GONE);
// }
}
#Override
public int getItemCount() {
return studentsArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
}
}
});
}
}
}
activity_view_students.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewStudents">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="409dp"
android:layout_height="729dp"
android:layout_marginEnd="1dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</androidx.recyclerview.widget.RecyclerView>
<Button
android:id="#+id/addStudentButton"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="Add Students"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/orderStudents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="orderStudents"
android:text="Order Students"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
daily_grading.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DailyGrading">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_student_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DailyGrading">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:foreground="?android:attr/selectableItemBackground"
app:cardElevation="2dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.cardview.widget.CardView>
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="52dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="50dp"
android:paddingTop="20dp"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_margin="10dp"
android:textSize="16sp" />
<CheckBox
android:id="#+id/passc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:text="PASS" />
<CheckBox
android:id="#+id/failc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:layout_toRightOf="#+id/passc"
android:text="FAIL" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
GradingRecyclerAdapter
package com.example.studenttracker;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class GradingRecyclerAdapter extends RecyclerView.Adapter<GradingRecyclerAdapter.ViewHolder> {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Students> studentsArrayList;
public GradingRecyclerAdapter(Context mContext, ArrayList<Students> studentsArrayList) {
this.mContext = mContext;
this.studentsArrayList = studentsArrayList;
}
#NonNull
#Override
public GradingRecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_grading_student_item,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//TextView
holder.textView.setText(studentsArrayList.get(position).getName());
Glide.with(mContext).load(studentsArrayList.get(position).getImageUrl()).into(holder.imageView);
}
#Override
public int getItemCount() {
return studentsArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
Button passButton;
Button failButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
passButton = itemView.findViewById(R.id.PASS);
failButton = itemView.findViewById(R.id.FAIL);
// passButton.setVisibility(View.GONE);
// failButton.setVisibility(View.GONE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
}
}
});
}
}
}
activity_grading_student_item
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DailyGrading">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:foreground="?android:attr/selectableItemBackground"
app:cardElevation="2dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.cardview.widget.CardView>
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="52dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="50dp"
android:paddingTop="20dp"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_margin="10dp"
android:textSize="16sp" />
<CheckBox
android:id="#+id/PASS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:text="PASS" />
<CheckBox
android:id="#+id/FAIL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:layout_toRightOf="#+id/PASS"
android:text="FAIL" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
You can simply use different adapters
create another activity_student_item.xml let's say activity_view_student_item.xml and remove the checkboxes from that one
create another adapter for that recyclerView but change
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_student_item,parent,false);
in the new adapter to
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_view_student_item,parent,false);
and in the ViewStudents activity set the recycler's Adapter to that new adapter

Android Studio RecyclerView wont show my data when i add toolbar at my `layout.xml` file

I created a page where it will show the firebase data in a RecyclerView. It work but I decided to put a toolbar at the top of the page to have a back function. After I put the toolbar in my layout file, the RecyclerView is not showing any data anymore. I think that my layout XML file is wrong. Thanks in advance for anyone helping.
Actity file
package com.example.attendanceappvqyfyp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.example.attendanceappvqyfyp.Interface.itemClickListener;
import com.example.attendanceappvqyfyp.Common.Common;
import com.example.attendanceappvqyfyp.Model.LecturerClass;
import com.example.attendanceappvqyfyp.Model.News;
import com.example.attendanceappvqyfyp.Model.Timetable;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.attendanceappvqyfyp.Common.Common;
public class LecturerClassList extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference lecturerclass;
DatabaseReference news;
FirebaseRecyclerAdapter<LecturerClass,LecturerClassViewHolder> adapter;
TextView newscourse, newsclass;
EditText newsdescription;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lecturer_class_list);
//Firebase
database = FirebaseDatabase.getInstance();
lecturerclass = database.getReference("Class");
news = database.getReference("News");
recyclerView = (RecyclerView)findViewById(R.id.recycler_lecturerclass);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Toolbar code
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Class List");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
loadLecturerClass(Common.currentLecturer.getName());
}
private void loadLecturerClass(String Lecturer) {
adapter = new FirebaseRecyclerAdapter<LecturerClass, LecturerClassViewHolder>(LecturerClass.class, R.layout.lecturerclass_item, LecturerClassViewHolder.class, lecturerclass.orderByChild("lecturer").equalTo(Lecturer)) {
#Override
protected void populateViewHolder(LecturerClassViewHolder lecturerClassViewHolder, LecturerClass lecturerClass, int i) {
lecturerClassViewHolder.lclasstitle.setText("Class :" + adapter.getRef(i).getKey());
lecturerClassViewHolder.ldate.setText("Day :" + lecturerClass.getDay());
lecturerClassViewHolder.ltime.setText("Time :" + lecturerClass.getTime());
lecturerClassViewHolder.lclassroom.setText("Classroom :" + lecturerClass.getClassroom());
lecturerClassViewHolder.lcourse.setText(lecturerClass.getCourse());
lecturerClassViewHolder.setItemClickListener(new itemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
//code later
}
});
}
};
recyclerView.setAdapter(adapter);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle().equals(Common.News))
{
showNewsDialog(adapter.getRef(item.getOrder()).getKey(),adapter.getItem(item.getOrder()));
}
return super.onContextItemSelected(item);
}
private void showNewsDialog(final String course, final LecturerClass item) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(LecturerClassList.this);
alertDialog.setTitle("Make Announcement");
alertDialog.setMessage("Make announcement about this class.");
LayoutInflater inflater = this.getLayoutInflater();
View lecturer_make_news = inflater.inflate(R.layout.activity_lecturer_make_news, null);
newscourse = lecturer_make_news.findViewById(R.id.NewsCourse);
newsclass = lecturer_make_news.findViewById(R.id.NewsClass);
newsdescription = lecturer_make_news.findViewById(R.id.NewsDescription);
newscourse.setText("Course: "+item.getCourse());
newsclass.setText("Subject: " + course);
alertDialog.setView(lecturer_make_news);
alertDialog.setPositiveButton("Post", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if(newsdescription.getText().toString().isEmpty()){
Toast.makeText(LecturerClassList.this, "Post cancel, description cannot be empty.", Toast.LENGTH_SHORT).show();
}
else {
News lnews = new News(
item.getCourse(),
course,
newsdescription.getText().toString()
);
news.child(String.valueOf(System.currentTimeMillis())).setValue(lnews);
Toast.makeText(LecturerClassList.this, "Announcement post successfully.", Toast.LENGTH_SHORT).show();
finish();
}
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();;
}
});
alertDialog.show();
}
}
Activity file for viewholder
package com.example.attendanceappvqyfyp;
import android.view.ContextMenu;
import android.view.View;
import android.widget.TextView;
import com.example.attendanceappvqyfyp.Common.Common;
import androidx.recyclerview.widget.RecyclerView;
import com.example.attendanceappvqyfyp.Interface.itemClickListener;
public class LecturerClassViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnCreateContextMenuListener {
public TextView lclasstitle, ldate, ltime, lclassroom, lcourse;
private itemClickListener itemClickListener;
public LecturerClassViewHolder(View itemView) {
super(itemView);
lclasstitle = (TextView)itemView.findViewById(R.id.lclasstitle);
ldate = (TextView)itemView.findViewById(R.id.ldate);
ltime = (TextView)itemView.findViewById(R.id.ltime);
lclassroom = (TextView)itemView.findViewById(R.id.lclassroom);
lcourse = (TextView)itemView.findViewById(R.id.lcourse);
itemView.setOnCreateContextMenuListener(this);
itemView.setOnClickListener(this);
}
public void setItemClickListener(itemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view, getAdapterPosition(), false);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select");
menu.add(0,0,getAdapterPosition(), Common.News);
}
}
Layout file for recyclerview
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LecturerClassList">
<android.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:theme="#style/ThemeOverlay.AppCompat.Dark" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_lecturerclass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constraintTop_toBottomOf="#+id/toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>
Layout file for itemview
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="160dp"
app:cardElevation="4dp"
android:layout_marginBottom="8dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/lclasstitle"
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/ldate"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignBottom="#id/lclasstitle"
android:layout_marginBottom="-40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/ltime"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignBottom="#id/ldate"
android:layout_marginBottom="-40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/lclassroom"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/lcourse"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:text=""
android:visibility="invisible"
android:textColor="#android:color/black"
android:textSize="20sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
Thanks to ZeePee for giving this link Display Back Arrow on Toolbar, although the toolbar didnt work for me, i change it back to actionbar and use the code from the link and it work.
Try adding horizontal constraints for Toolbar and Recycler View. After that you need to specify where do you want your single item widgets in Relative layout

Timetable android application not working

I have made an android application, and its getting successfully compiled without any errors. But when I run app in my android phone, then it does not show the desired output.
This is my MainActivity.java:
package wahab.com.timetabledemo;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUIViews();
initToolbar();
}
private void setupUIViews(){
toolbar = (Toolbar)findViewById(R.id.ToolbarMain);
listView = (ListView)findViewById(R.id.lvMain);
}
private void initToolbar(){
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("TimeTable App");
}
private void setupListView(){
String[] title = getResources().getStringArray(R.array.Main);
String[] description = getResources().getStringArray(R.array.Description);
SimpleAdaptor simpleAdaptor = new SimpleAdaptor(this, title, description);
listView.setAdapter(simpleAdaptor);
}
public class SimpleAdaptor extends BaseAdapter{
private Context mContext;
private LayoutInflater layoutInflater;
private TextView title, description;
private String[] titleArray;
private String[] descriptionArray;
private ImageView imageView;
public SimpleAdaptor(Context context, String[] title, String[] description){
mContext = context;
titleArray = title;
descriptionArray = description;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return titleArray.length;
}
#Override
public Object getItem(int i) {
return titleArray[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null){
view = layoutInflater.inflate(R.layout.main_activity_single_item,null);
}
title = (TextView)view.findViewById(R.id.tvMain);
description = (TextView)view.findViewById(R.id.tvDescription);
imageView = (ImageView)view.findViewById((R.id.ivMain));
title.setText(titleArray[i]);
description.setText(descriptionArray[i]);
if(titleArray[i].equalsIgnoreCase("Timetable")){
imageView.setImageResource(R.drawable.timetable);
}
else if(titleArray[i].equalsIgnoreCase("Subjects")){
imageView.setImageResource(R.drawable.book);
}
else if(titleArray[i].equalsIgnoreCase("Faculty")){
imageView.setImageResource(R.drawable.contact);
}
else{
imageView.setImageResource(R.drawable.settings);
}
return view;
}
}
}
The given above is a error free code.
This is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="wahab.com.timetabledemo.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/ToolbarMain"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="#color/colorPrimary"
app:titleTextColor="#color/white">
</android.support.v7.widget.Toolbar>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lvMain"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:dividerHeight="10dp"
android:layout_below="#+id/ToolbarMain"
android:divider="#null">
</ListView>
</RelativeLayout>
In my activity_main.xml, I have used a RelativeLayout in which I have defined a Toolbar and a ListView. A ListView is defined so that I can add different list of operation.
This is my main_activity_single_item.xml:
<android.support.v7.widget.CardView android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/colorAccent"
android:elevation="4dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="80dp"
android:layout_height="105dp"
android:id="#+id/ivMain"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvMain"
android:textStyle="bold"
android:text="Timetable"
android:layout_marginTop="6dp"
android:layout_marginLeft="6dp"
android:layout_toRightOf="#+id/ivMain"
android:textSize="25sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvDescription"
android:text="description"
android:layout_marginLeft="6dp"
android:layout_marginTop="3dp"
android:layout_below="#+id/tvMain"
android:layout_toRightOf="#+id/ivMain"
android:textSize="16sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvClick"
android:textSize="12sp"
android:text="click to know more"
android:layout_marginTop="6dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/tvDescription"
android:layout_alignBottom="#+id/ivMain"/>
</RelativeLayout>
In this above xml file, I have created a CardView which will consist of an ImageView and 3 TextView, which is placed using a RelativeLayout.
So, my code is getting compiled properly and my app is also running but am not getting the desired output.
You need to call setupListView() in onCreate to display the list
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUIViews();
initToolbar();
setupListView(); // to display list
^^^^^^^^^^
}

CardView setCardBackgroundColor won't work

I have made an adapter of CardView through the RecyclerView for me to use the same template of card for this feature of mine.
The objective is to create certain cards with different colors, based on the parameter inc_status in INCCards.java. But it doesn't just seem to work.
Here's the source code for the template card:
item_inc_card.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/spacing_medium"
android:paddingRight="#dimen/spacing_medium"
android:paddingTop="#dimen/spacing_medium"
android:background="#color/tertiary">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="#dimen/spacing_none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/spacing_large"
android:paddingRight="#dimen/spacing_large"
android:paddingTop="#dimen/spacing_large"
android:paddingBottom="#dimen/spacing_medium"
android:id="#+id/relative_layout">
<TextView
android:id="#+id/course_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textColor="#color/white"
android:textSize="#dimen/text_headline"
android:text="#string/course_code"
android:textStyle="bold"/>
<TextView
android:id="#+id/course_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/course_code"
android:textColor="#color/white"
android:textSize="#dimen/text_subhead"
android:text="#string/course_title" />
<TextView
android:id="#+id/faculty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:layout_below="#+id/course_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textStyle="italic"
android:textSize="#dimen/text_body"
android:text="#string/faculty" />
<ImageView
android:id="#+id/status_icon"
android:src="#drawable/icon_avatar"
android:layout_width="#dimen/size_user_icon"
android:layout_height="#dimen/size_user_icon"
android:layout_above="#+id/faculty"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/inc_grade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_body"
android:layout_below="#+id/status_icon"
android:layout_alignRight="#+id/status_icon"
android:layout_alignEnd="#+id/status_icon"
android:layout_alignLeft="#+id/status_icon"
android:layout_alignStart="#+id/status_icon"
android:gravity="center"
android:textAlignment="center"
android:textColor="#color/white"
android:text="#string/equiv_grade"/>
</RelativeLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="0.001dp"
android:background="#FFFFFF"
android:id="#+id/line_divider"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/spacing_large"
android:paddingRight="#dimen/spacing_medium"
android:paddingBottom="#dimen/spacing_medium"
android:layout_marginTop="#dimen/spacing_medium"
android:id="#+id/semesterInfoLinearLayout">
<TextView
android:id="#+id/section"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_caption"
android:text="#string/section"
android:textColor="#color/white"
android:layout_weight="0.33" />
<TextView
android:id="#+id/semester"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_caption"
android:text="#string/semester"
android:textColor="#color/white"
android:layout_weight="0.33"
android:gravity="center" />
<TextView
android:id="#+id/acad_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_caption"
android:text="#string/acad_year"
android:textColor="#color/white"
android:layout_weight=".33"
android:gravity="right" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
And for the fragment layout:
item_inc_card.xml
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_inc_cards"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/tertiary"/>
To where each card is initialized by the object
INCCards.java
package ph.edu.amitypipduo.myiit;
public class INCCards {
String course_code, course_title, faculty, section, semester, acad_year;
int inc_status, status_icon;
final String inc_grade = "INC 3.00";
public INCCards(String course_code, String course_title, String faculty, String section, String semester, String acad_year, String inc_status) {
this.course_code = course_code;
this.course_title = course_title;
this.faculty = faculty;
this.section = section;
this.semester = semester;
this. acad_year = acad_year;
switch (inc_status) {
case "notice":
this.inc_status = R.color.inc_notice;
this.status_icon = R.drawable.inc_notice;
break;
case "alert":
this.inc_status = R.color.inc_alert;
this.status_icon = R.drawable.inc_alert;
break;
case "warning":
this.inc_status = R.color.inc_warning;
this.status_icon = R.drawable.inc_warning;
break;
case "danger":
this.inc_status = R.color.inc_danger;
this.status_icon = R.drawable.inc_danger;
break;
}
}
}
I tried setting the background color of the card at method onBindViewHolder by:
cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);
as seen here in
INCAdapter.java
package ph.edu.amitypipduo.myiit;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class INCAdapter extends RecyclerView.Adapter<INCAdapter.CardViewHolder> {
List<INCCards> inc_cards;
public INCAdapter(List<INCCards> inc_cards){
this.inc_cards = inc_cards;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_inc_card, viewGroup, false);
CardViewHolder card_view_holder = new CardViewHolder(view);
return card_view_holder;
}
#Override
public void onBindViewHolder(CardViewHolder cardViewHolder, int i) {
cardViewHolder.course_code.setText(inc_cards.get(i).course_code);
cardViewHolder.course_title.setText(inc_cards.get(i).course_title);
cardViewHolder.faculty.setText(inc_cards.get(i).faculty);
cardViewHolder.section.setText(inc_cards.get(i).section);
cardViewHolder.semester.setText(inc_cards.get(i).semester);
cardViewHolder.acad_year.setText(inc_cards.get(i).acad_year);
cardViewHolder.inc_grade.setText(inc_cards.get(i).inc_grade);
cardViewHolder.status_icon.setImageResource(inc_cards.get(i).status_icon);
cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);
}
#Override
public int getItemCount() {
return inc_cards.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class CardViewHolder extends RecyclerView.ViewHolder {
CardView card_view;
TextView course_code, course_title, faculty, section, semester, acad_year, inc_grade;
ImageView status_icon;
CardViewHolder(View itemView) {
super(itemView);
card_view = (CardView) itemView.findViewById(R.id.card_view);
course_code = (TextView) itemView.findViewById(R.id.course_code);
course_title = (TextView) itemView.findViewById(R.id.course_title);
faculty = (TextView) itemView.findViewById(R.id.faculty);
inc_grade = (TextView) itemView.findViewById(R.id.inc_grade);
section = (TextView) itemView.findViewById(R.id.section);
semester = (TextView) itemView.findViewById(R.id.semester);
acad_year = (TextView) itemView.findViewById(R.id.acad_year);
status_icon = (ImageView) itemView.findViewById(R.id.status_icon);
}
}
}
Then initializing the data in the fragment class and inflating the layout:
INCMonitorFragment.java
package ph.edu.amitypipduo.myiit;
import android.app.Activity;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class INCMonitorFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private RecyclerView recycler_view;
private LinearLayoutManager linear_layout_manager;
private INCAdapter inc_adapter;
private List<INCCards> inc_cards;
private void initializeData() {
inc_cards = new ArrayList<>();
inc_cards.add(new INCCards("CSC 198", "Methods of Research", "Prof. Cyrus Gabilla", "CS-1A", "SECOND SEMESTER", "AY 2014-2015", "danger"));
inc_cards.add(new INCCards("POLSCI 2", "Philippine Govt. & Const.", "Prof. Cyrus Gabilla", "AB4", "SUMMER SEMESTER", "AY 2013-2014", "warning"));
inc_cards.add(new INCCards("ENG 2N", "Writing in Discipline", "Prof. Rabindranath Polito", "B4", "FIRST SEMESTER", "AY 2012-2013", "alert"));
inc_cards.add(new INCCards("MATH 51", "I Forgot the Course Title", "Prof. Forgotten Name", "69", "SECOND SEMESTER", "AY 2012-2013", "notice"));
}
// TODO: Rename and change types and number of parameters
public static INCMonitorFragment newInstance(String param1, String param2) {
INCMonitorFragment fragment = new INCMonitorFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public INCMonitorFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
initializeData();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_inc_monitor, container, false);
recycler_view = (RecyclerView) view.findViewById(R.id.fragment_inc_cards);
recycler_view.setHasFixedSize(true);
linear_layout_manager = new LinearLayoutManager(getActivity().getApplicationContext());
recycler_view.setLayoutManager(linear_layout_manager);
inc_adapter = new INCAdapter(inc_cards);
recycler_view.setAdapter(inc_adapter);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
But it only shows this:
Why does it not recognize the color? How come the R.drawable..... was recognized by the onBindViewHolder and not the R.color.....?
Change
cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);
to
int colorId = inc_cards.get(i).inc_status;
int color = cardViewHolder.card_view.getContext().getResources().getColor(colorId);
cardViewHolder.card_view.setCardBackgroundColor(color);
You are using the value from R.color instead of the value you set in your XML.
I'm getting a more reliable color overriding with this line:
setBackgroundTintList(ColorStateList.valueOf(color));
instead of:
setCardBackgroundColor(color).
One thing to add, make sure you have the alpha in your color number and if you don't just add ff at the begining of your color, otherwise it won't work correctly.
For example this works
view.setCardBackgroundColor(0xff2ecc71)
While this one shows a white background
view.setCardBackgroundColor(0x2ecc71)
Try to use Material Card View Instead
then Do something LIke this:
private MaterialCardView imgIgnition;
imgIgnition = findViewById(R.id.imgIgnition);
imgIgnition.setCardBackgroundColor(Color.parseColor("#198754"));

Categories