CardView not displaying within RecyclerView - android

Before you ask, yes I know there are many questions that are very similar to this and I have tried most of them to no avail. My problem is that a CardView is not displaying within a RecyclerView. The items whithin it are displaying but not the card itself.
Without further or do, here's my code:
Adapter:
Integer count = 0;
Boolean isStart = true;
String datag = "";
String typeg = "";
Integer LastItemType=0; //0=None 1=Text 2=Image
ViewHolder a;
#Override
public EntryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
a= createholder(parent, viewType);
return(a);
}
public ViewHolder createholder(ViewGroup parent, int viewtype) {
if (typeg.equals("image")) {
View root = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listitems, parent, false);
CardView card = (CardView) root.findViewById(R.id.card_view);
ImageView image = (ImageView) root.findViewById(R.id.Img);
((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.card_view));
if (LastItemType == 2) {
((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.Img));
}
if (LastItemType == 1) {
((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.Txt));
}
ViewHolder vh = new ViewHolder(image, card);
LastItemType = 2;
return vh;
} else {
if (typeg.equals("text")) {
View root = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listitems, parent, false);
CardView card = (CardView) root.findViewById(R.id.card_view);
TextView image = (TextView) root.findViewById(R.id.Txt);
((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.card_view));
if (LastItemType == 1) {
((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.Txt));
}
if (LastItemType == 2) {
((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.Img));
}
ViewHolder vh = new ViewHolder(image, card);
LastItemType = 1;
return vh;
}
return null; //TODO: REMOVE!
}
}
#Override
public void onBindViewHolder(EntryAdapter.ViewHolder holder, int position) {
// Deal with data
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imgg;
public TextView txtg;
public CardView cardg;
public ViewHolder(ImageView image, CardView card) {
super(image);
imgg = image;
cardg = card;
}
public ViewHolder(TextView text, CardView card) {
super(text);
txtg = text;
cardg = card;
}
}
#Override
public int getItemCount() {
return count;
}
public void refresh(String data, String type, ViewGroup parent) {
isStart = false;
datag = data;
typeg = type;
count++;
createholder(parent, -100);
}
listitems.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="200dp"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
>
<ImageView
android:layout_height="wrap_content"
android:layout_weight="0.25"
android:layout_width="wrap_content"
android:layout_margin="10dp"
android:id="#+id/Img"
android:scaleType="center"
android:maxHeight="100dp"
android:maxWidth="150dp"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="0.25"
android:id="#+id/Txt"
android:layout_gravity="center_horizontal|center_vertical"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Thanks in advance!

Check out my code, i use it for each of my app after modifying it slightly. You can also use adapter if you have more than one RecyclerViews by changing it's type field and layout and views accordingly. It contains a CoordinatorLayout that has CollapsingLayout with ImageView in it. It contains many layouts for Material Design, i hope it helps.
Activity contains RecyclerView and CardView, i removed things like database, Floating action buttons that you may not need and may make it more difficult to understand. If you need the whole class contact me.
public class MeasureListActivity extends AppCompatActivity
implements MeasureListAdapter.OnRecyclerViewMeasureClickListener {
// Views
private RecyclerView mRecyclerView;
private MeasureListAdapter mAdapter;
private Toolbar toolbar;
// List that keeps values displayed on the screen
private List<Measure> listMeasure;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prev_measures);
setViews();
}
private void setViews() {
/*
* Set toolbar and arrow icon to return back
*/
toolbar = (Toolbar) findViewById(R.id.toolbarPrevMeasure);
setSupportActionBar(toolbar);
// Enable home button for API < 14
getSupportActionBar().setHomeButtonEnabled(true);
// Enable home button for API >= 14
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/*
* RecylerView to display items as a list
*/
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerViewPrevMeasure);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new MeasureListAdapter(this, listMeasure, 0);
// Attach an instance of OnRecyclerViewMeasureClickListener that
// implements itemClicked()
mAdapter.setClickListener(this);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void itemMeasureClicked(View view, int position) {
}
}
public class MeasureListAdapter extends RecyclerView.Adapter<MeasureListAdapter.MyViewHolder> {
private LayoutInflater inflater;
private List<Measure> data = Collections.emptyList();
// This is for delegating event from adapter's onClick() method to
// NavigationDrawerFragment
private OnRecyclerViewMeasureClickListener recyclerClickListener;
private DecimalFormat decimalFormat;
private int type = 0;
private Context mContext;
public MeasureListAdapter(Context context, List<Measure> data, int type) {
mContext = context;
inflater = LayoutInflater.from(context);
this.data = data;
decimalFormat = new DecimalFormat("###.#");
this.type = type;
}
#Override
public int getItemCount() {
return data.size();
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
Measure measure = data.get(position);
String title = measure.getTitle();
String note = measure.getNote();
String date = measure.getFormattedDate();
double angle = measure.getAnglePhoto();
// Compass
double azimuth = measure.getAngleAzimuth();
double pitch = measure.getAnglePitch();
double roll = measure.getAngleRoll();
String bearing = measure.getBearing();
holder.tvTitle.setText(title);
holder.tvNote.setText(note);
holder.tvAngle.setText(
mContext.getString(R.string.angle) + ": " + decimalFormat.format(angle) + ConstantsApp.DEGREE_ICON);
// Compass
holder.tvAzimuth.setText(
mContext.getString(R.string.azimuth) + ": " + decimalFormat.format(azimuth) + ConstantsApp.DEGREE_ICON);
holder.tvPitch.setText(
mContext.getString(R.string.pitch) + ": " + decimalFormat.format(pitch) + ConstantsApp.DEGREE_ICON);
holder.tvRoll.setText(
mContext.getString(R.string.roll) + ": " + decimalFormat.format(roll) + ConstantsApp.DEGREE_ICON);
holder.tvBearing.setText(mContext.getString(R.string.bearing) + " " + bearing);
holder.tvDate.setText("Date" + ": " + measure.getFormattedDate());
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
View view = null;
view = inflater.inflate(R.layout.custom_row_angle_photo, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
/**
* get an instance of OnRecyclerViewClickListener interface
*
* #param OnRecyclerViewMeasureClickListener
* callback that is used by adapter to invoke the method of the
* class implements the OnRecyclerViewClickListener interface
*/
public void setClickListener(OnRecyclerViewMeasureClickListener recyclerClickListener) {
this.recyclerClickListener = recyclerClickListener;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
// Views
private TextView tvTitle, tvNote, tvAngle, tvAzimuth, tvPitch, tvRoll, tvBearing, tvDate;
public MyViewHolder(View itemView) {
super(itemView);
tvTitle = (TextView) itemView.findViewById(R.id.tvDisplayTitle);
tvAngle = (TextView) itemView.findViewById(R.id.tvDisplayAngle);
// Compass
tvAzimuth = (TextView) itemView.findViewById(R.id.tvDisplayAzimuth);
tvPitch = (TextView) itemView.findViewById(R.id.tvDisplayPitch);
tvRoll = (TextView) itemView.findViewById(R.id.tvDisplayRoll);
tvBearing = (TextView) itemView.findViewById(R.id.tvDisplayBearing);
tvNote = (TextView) itemView.findViewById(R.id.tvDisplayNote);
tvDate = (TextView) itemView.findViewById(R.id.tvDisplayDate);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (recyclerClickListener != null) {
recyclerClickListener.itemMeasureClicked(v, getLayoutPosition());
}
}
}
/**
* RecyclerViewClickListener interface helps user to set a clickListener to
* the RecyclerView. By setting this listener, any item of Recycler View can
* respond to any interaction.
*
* #author Fatih
*
*/
public interface OnRecyclerViewMeasureClickListener {
/**
* This is a callback method that be overriden by the class that
* implements this interface
*/
public void itemMeasureClicked(View view, int position);
}
}
Measure class only contains setters and getters for int and String values so i don't put it.
Layout for Activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layoutMainMeasure"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:background="#android:color/background_light"
android:paddingBottom="50dp" >
<android.support.design.widget.AppBarLayout
android:id="#+id/appbarPrevMeasure"
android:layout_width="match_parent"
android:layout_height="200dp"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" >
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsingToolbarPrevMeasure"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|enterAlwaysCollapsed"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp" >
<ImageView
android:id="#+id/backgroundPrevMeasure"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_collapseMode="parallax"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
android:src="#drawable/bg_material" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarPrevMeasure"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerViewPrevMeasure"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#eeeeee"
android:paddingTop="12dp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabLog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="80dp"
app:layout_anchor="#id/appbarPrevMeasure"
app:layout_anchorGravity="bottom|right|end"
android:src="#drawable/ic_save_white_36dp"
android:tint="#android:color/white"
app:backgroundTint="#FFA500" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabClearDB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/activity_horizontal_margin"
app:layout_anchor="#id/appbarPrevMeasure"
app:layout_anchorGravity="bottom|right|end"
android:src="#drawable/ic_delete_white_36dp"
android:tint="#android:color/white"
app:backgroundTint="#D463C3" />
</android.support.design.widget.CoordinatorLayout>
Layout for adapter rows with CardView
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardRecord"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#eeeeee"
cardview:cardCornerRadius="5dp"
cardview:cardElevation="5dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp" >
<TextView
android:id="#+id/tvDisplayTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:textColor="#FF0000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvDisplayAngle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:text="#string/angle_"
android:textColor="#525657"
android:textSize="18sp" />
<TextView
android:id="#+id/tvDisplayAzimuth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:text="#string/angle_"
android:textColor="#525657"
android:textSize="14sp" />
<TextView
android:id="#+id/tvDisplayBearing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:text="#string/angle_"
android:textColor="#525657"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvDisplayPitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="12dp"
android:text="#string/angle_"
android:textColor="#525657"
android:textSize="14sp" />
<TextView
android:id="#+id/tvDisplayRoll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="12dp"
android:text="#string/angle_"
android:textColor="#525657"
android:textSize="14sp" />
</LinearLayout>
<TextView
android:id="#+id/tvDisplayDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="#string/date_"
android:textColor="#9EA9AD"
android:textSize="14sp" />
<TextView
android:id="#+id/tvDisplayNote"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text=""
android:textColor="#828A8C"
android:textSize="14sp" />
</LinearLayout>
How it looks

Does your RecyclerView show ImageView or TextView only?
If yes, because your ViewHolder Constructor is wrong. You have to call super(itemView) in your ViewHolder's Constructor, itemView is the view which is displayed as a row in RecyclerView. To fix your issue, I think you should change your code as below:
public ViewHolder createholder(ViewGroup parent, int viewtype) {
if (typeg.equals("image") || typeg.equals("text")) {
View root = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listitems, parent, false);
return new ViewHolder(root, typeg.equals("text"));
}
//FIXME: As my expericence you should NOT return null for ViewHolder. You have to sure the typeg is one of "image" or "text". I think you should change typeg to Boolean variable to not return null ViewHolder.
return null;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imgg;
public TextView txtg;
public CardView cardg;
public ViewHolder(View itemView, boolean isTypeText) {
super(itemView);
imgg = (ImageView) itemView.findViewById(R.id.Img);
cardg = (CardView) itemView.findViewById(R.id.card_view);
txtg = (TextView) itemView.findViewById(R.id.Txt);
imgg.setVisibility(isTypeText ? View.GONE : View.VISIBLE);
txtg.setVisibility(isTypeText ? View.VISIBLE : View.GONE);
}
}

Here is the proper Documentation Read and And Follow it.
You must be Doing Something Wrong in Gradle.!
so, the issue was Your XML was not showing CardView in it here we go.!
Add following Dependencies.!
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
testCompile 'junit:junit:4.12'
Here is Your XML is Working Perfectly Fine.!
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="200dp"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
>
<ImageView
android:layout_height="wrap_content"
android:layout_weight="0.25"
android:layout_width="wrap_content"
android:layout_margin="10dp"
android:id="#+id/Img"
android:scaleType="center"
android:maxHeight="100dp"
android:maxWidth="150dp"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="0.25"
android:id="#+id/Txt"
android:layout_gravity="center_horizontal|center_vertical"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Now Clean and Rebuild Your Project.!
ok try this its Working Fine.now.!

Is it because you are removing card_view like so?
((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.card_view));

Related

Can't set RecyclerView inside CardView?

I'm trying to put a RecyclerView inside a CardView and create items dynamically.
Obviously, in XML, RecyclerView is set inside CardView tag, but as you can see picture, RecyclerView item is created outside CardView.
(RecyclerView's items are the parts expressed as kg and set in the photo. And CardView is also an item of another RecyclerView.)
What's the problem?
XML
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="12dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
app:cardElevation="10dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/ll1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/workout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="TEST"/>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/light_blue_400"/>
</LinearLayout>
<LinearLayout
android:id="#+id/ll2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintTop_toBottomOf="#+id/ll1">
<com.google.android.material.button.MaterialButton
android:id="#+id/delete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="8dp"
android:layout_marginEnd="4dp"
style="#style/RoutineButtonStyle"
android:text="DELETE"
app:icon="#drawable/ic_delete"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="4dp"
android:layout_marginEnd="8dp"
style="#style/RoutineButtonStyle"
android:text="ADD"
app:icon="#drawable/ic_add"/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/ll2"
android:orientation="vertical"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Let me know if you need any other code.
Here is the Activity of your add/delete CardView:
//Item List if you want to add one or more Items
private List<MyItem> myItems = new ArrayList<>();
private Adapter smallCardAdapter;
private int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.rv);
//Creates a new Object in the Adapter.class
smallCardAdapter = new Adapter();
recyclerView.setAdapter(smallCardAdapter);
CardView cardView = findViewById(R.id.cardView);
MaterialButton delete = findViewById(R.id.delete);
MaterialButton add = findViewById(R.id.add);
//Add onClickListener
add.setOnClickListener(v -> {
try {
size = myItems.size();
//if the value is 0, a new item is created
//if you want to delete the card after 0 than you have to change the value to 0
if(size == 0){
//Creates a new Object in the MyItem.class
myItems.add(new MyItem("Set","1kg"));
}else{
MyItem myItem = myItems.get(0);
//Replace kg with "" to make a Integer
String secondString = myItem.getSecondString().replace("kg","");
Integer value = Integer.valueOf(secondString);
value++;
myItem.setSecondString(value+"kg");
myItems.set(0,myItem);
}
updateAdapter();
}catch (Exception e){
Log.w("MainActivity","Add Button OnClickListener");
e.printStackTrace();
}
});
//Delete onClickListener
delete.setOnClickListener(v->{
try {
size = myItems.size();
//If the value is 0 then canceled to avoid errors
if(size == 0){
return;
}
MyItem myItem = myItems.get(0);
//Replace kg with "" to make a Integer
String secondString = myItem.getSecondString().replace("kg","");
Integer value = Integer.valueOf(secondString);
//if the value is one or lower
if(value <= 1){
//The card will deleted after updateAdapter();
myItems.clear();
}else{
value--;
myItem.setSecondString(value+"kg");
myItems.set(0,myItem);
}
updateAdapter();
}catch (Exception e){
Log.w("MainActivity","Delete Button OnClickListener");
e.printStackTrace();
}
});
}
private void updateAdapter(){
try {
smallCardAdapter.setItems(myItems);
}catch (Exception e){
Log.w("MainActivity","updateAdapter");
e.printStackTrace();
}
}
The custom Item called MyItem:
public class MyItem {
String firstString;
String secondString;
public MyItem(String firstString,String secondString){
this.firstString = firstString;
this.secondString = secondString;
}
public String getFirstString() {
return firstString;
}
public void setFirstString(String firstString) {
this.firstString = firstString;
}
public String getSecondString() {
return secondString;
}
public void setSecondString(String secondString) {
this.secondString = secondString;
}
}
The Adapter.java creates a smallCard:
public class Adapter extends RecyclerView.Adapter<Adapter.SmallCardHolder> {
private List<MyItem> items = new ArrayList<>();
#NonNull
#Override
public SmallCardHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// I created a new smallcard for the CardView
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.smallcard, parent, false);
SmallCardHolder smallCardHolder = new SmallCardHolder(itemView);
return smallCardHolder;
}
#Override
public void onBindViewHolder(#NonNull final SmallCardHolder holder, int position) {
//get the current item of the position
MyItem myItem = items.get(position);
String firstString = myItem.getFirstString();
String secondString = myItem.getSecondString();
holder.textViewSet.setText(firstString);
holder.textViewkg.setText(secondString);
}
#Override
public int getItemCount () {
return items.size();
}
public void setItems(List <MyItem> items) {
this.items = items;
notifyDataSetChanged();
}
class SmallCardHolder extends RecyclerView.ViewHolder {
//Here are the TextView's of the smallcard (smallcard.xml)
private TextView textViewSet;
private TextView textViewkg;
public SmallCardHolder(#NonNull View itemView) {
super(itemView);
textViewSet = itemView.findViewById(R.id.set);
textViewkg = itemView.findViewById(R.id.kg);
}
}
}
Create a new layout with name called smallcard.xml for the Adapter.java:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/set"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"
android:layout_centerVertical="true"
android:textSize="18sp"
android:layout_marginStart="5dp"
android:textColor="?attr/colorPrimary"
android:textStyle="bold"/>
<TextView
android:id="#+id/kg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kg"
android:layout_toRightOf="#id/set"
android:layout_marginLeft="55dp"
android:layout_centerVertical="true"
android:textColor="?attr/colorPrimary"
android:textSize="16sp"
android:layout_marginRight="10dp"
android:maxLines="1"/>
</RelativeLayout>
</RelativeLayout>
In your XML you have to give the CardView a name. I called it cardView. Here is the code android:id="#+id/cardView"
Result:
You will find more information as comments in the code.

Bug in recycle grid. Changing UI without click randomly

I have a recycler inside fragment in view pager.
The problem that it put likes on user accounts in UI randomly but in DB everything is fine.
In logs, I see that random is not influence on BD. So the bug is only in UI part. After the refresh of the list, it can appear again and after that disappear.
I would like to share code but I already don't have an I idea where the problem could be. It might be in adapter/refresh list listener / XML or any other places. Please let me know what part of the code you need and I will provide it. Maybe it is a bug of recycler as itself and I can't fix it.
Adapter class code:
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.UserViewHolder>{
private List<FsUser> fsUserList = new ArrayList<>();
private OnItemClickListener.OnItemClickCallback onItemClickCallback;
private OnItemClickListener.OnItemClickCallback onChatClickCallback;
private OnItemClickListener.OnItemClickCallback onLikeClickCallback;
private Context context;
public SearchAdapter(OnItemClickListener.OnItemClickCallback onItemClickCallback,
OnItemClickListener.OnItemClickCallback onChatClickCallback,
OnItemClickListener.OnItemClickCallback onLikeClickCallback) {
this.onItemClickCallback = onItemClickCallback;
this.onChatClickCallback = onChatClickCallback;
this.onLikeClickCallback = onLikeClickCallback;
}
public void addUsers(List<FsUser> userList) {
fsUserList.addAll(userList);
notifyItemRangeInserted(fsUserList.size() - userList.size(), fsUserList.size());
}
public void clearData(){
fsUserList.clear();
notifyDataSetChanged();
}
#NonNull
#Override
public UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user, parent, false);
return new UserViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull UserViewHolder holder, int position) {
FsUser fsUser = fsUserList.get(position);
holder.bind(fsUser, position);
}
#Override
public int getItemCount() {
return fsUserList.size();
}
public String getLastItemId(){
return fsUserList.get(fsUserList.size() - 1).getUid();
}
class UserViewHolder extends RecyclerView.ViewHolder {
RelativeLayout container;
ImageView imageView, like, chat;
TextView name, country;
private LottieAnimationView animationView;
UserViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
container = itemView.findViewById(R.id.item_user_container);
imageView = itemView.findViewById(R.id.user_img);
like = itemView.findViewById(R.id.search_btn_like);
chat = itemView.findViewById(R.id.search_btn_chat);
name = itemView.findViewById(R.id.user_name);
country = itemView.findViewById(R.id.user_country);
animationView = itemView.findViewById(R.id.lottieAnimationView);
}
void bind(FsUser fsUser, int position){
ViewCompat.setTransitionName(imageView, fsUser.getName());
if (FirebaseUtils.isUserExist() && fsUser.getUid() != null) {
new FriendRepository().isLiked(fsUser.getUid(), flag -> {
if (flag) {
like.setBackground(ContextCompat.getDrawable(context, R.drawable.ic_favorite));
animationView.setVisibility(View.VISIBLE);
}
});
}
if(fsUser.getUid() != null) {
chat.setOnClickListener(new OnItemClickListener(position, onChatClickCallback));
like.setOnClickListener(new OnItemClickListener(position, onLikeClickCallback));
}
imageView.setOnClickListener(new OnItemClickListener(position, onItemClickCallback));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
if(fsUser.getImage().equals("default")){
Glide.with(context).load(context.getResources().getDrawable(R.drawable.default_avatar)).into(imageView);
} else {
Glide.with(context).load(fsUser.getImage()).thumbnail(0.5f).into(imageView);
}
name.setText(fsUser.getName());
country.setText(fsUser.getCountry());
ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f).setDuration(500);
animator.addUpdateListener(valueAnimator ->
animationView.setProgress((Float) valueAnimator.getAnimatedValue()));
if (animationView.getProgress() == 0f) {
animator.start();
} else {
animationView.setProgress(0f);
}
}
}
}
And xml file of RecyclerView item:
<?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"
android:id="#+id/item_user_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="#dimen/user_cv_width"
android:layout_height="#dimen/user_cv_height"
android:layout_margin="#dimen/dp4"
android:elevation="#dimen/dp4">
<RelativeLayout
android:id="#+id/item_user_main_relative_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/item_user_top_relative_container"
android:layout_width="#dimen/user_rl_width"
android:layout_height="#dimen/user_rl_height">
<ImageView
android:id="#+id/user_img"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerCrop"
android:src="#drawable/default_avatar" />
<RelativeLayout
android:id="#+id/item_user_top_relative"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/user_item_bg"
android:orientation="vertical">
<TextView
android:id="#+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/dp4"
android:textColor="#android:color/white"
android:textSize="#dimen/medium_text_size" />
<TextView
android:id="#+id/user_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:layout_marginStart="#dimen/dp4"
android:textSize="#dimen/medium_text_size" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/item_user_bottom_relative_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/dp12">
<ImageView
android:id="#+id/search_btn_like"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/heart_outline"
android:contentDescription="#string/search_btn_like_desc"/>
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/lottieAnimationView"
android:visibility="gone"
android:layout_width="#dimen/lottie_animation_view_size"
android:layout_height="#dimen/lottie_animation_view_size"
app:lottie_loop="true"
app:lottie_autoPlay="true"
app:lottie_fileName="like.json"/>
</RelativeLayout>
<ImageView
android:id="#+id/search_btn_chat"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/dp12"
android:layout_weight="1"
android:src="#drawable/message_outline" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
Override this two methods inside your adapter
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}

How to remove redundancy item in CardView layout

I'm using a CardView Layout in a RecyclerView, JSON will load data and fill the adapter. My layout includes a ImageView, a TextView and everything is fine.
This is the Adapter class (UPDATED):
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private static final int TYPE_HEADER = 4;
private static final int TYPE_ITEM = 1;
Context context;
List<CarData> getCarData; // getDataAdapter
ImageLoader imageThumbLoader;
public RecyclerViewAdapter(List<CarData> getCarData, Context context){
super();
this.getCarData = getCarData;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
// if (!isPositionHeader(position)) {
CarData getCarData1 = getCarData.get(position - 1);
imageThumbLoader = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageThumbLoader.get(getCarData1.getImageThumb(),
ImageLoader.getImageListener(
Viewholder.imageThumb,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.imageThumb.setImageUrl(getCarData1.getImageThumb(), imageThumbLoader);
Viewholder.titleName.setText(getCarData1.getTitleName());
Viewholder.doorName.setText(Html.fromHtml("<b>Số cửa:</b> " + getCarData1.getDoorName()));
Viewholder.seatName.setText(Html.fromHtml("<b>Số ghế:</b> " + getCarData1.getSeatName()));
Viewholder.cityName.setText(Html.fromHtml(getCarData1.getCityName()));
Viewholder.districtName.setText(Html.fromHtml(getCarData1.getDistrictName()));
// }
}
public int getDataAdapter() {
return getCarData == null ? 0 : getCarData.size();
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position)) {
return TYPE_HEADER;
}
return TYPE_ITEM;
}
#Override
public int getItemCount() {
return getDataAdapter(); // + 1
}
private boolean isPositionHeader(int position) {
return position == 0;
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView titleName;
public NetworkImageView imageThumb;
public TextView doorName;
public TextView seatName;
public TextView cityName;
public TextView districtName;
public ViewHolder(View itemView) {
super(itemView);
titleName = (TextView) itemView.findViewById(R.id.titleName);
imageThumb = (NetworkImageView) itemView.findViewById(R.id.imageThumb);
doorName = (TextView) itemView.findViewById(R.id.doorName);
seatName = (TextView) itemView.findViewById(R.id.seatName);
cityName = (TextView) itemView.findViewById(R.id.cityName);
districtName = (TextView) itemView.findViewById(R.id.districtName);
}
}
}
My layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="3dp"
card_view:contentPadding="3dp"
card_view:cardCornerRadius="3dp"
card_view:cardMaxElevation="3dp"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/imageThumb"
android:layout_width="400dp"
android:layout_height="230dp"
android:src="#mipmap/ic_launcher"
android:gravity="top"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/titleName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Image View"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imageThumb"
android:layout_toEndOf="#+id/imageThumb"
android:layout_marginLeft="20dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/doorName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/seatName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/cityName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/districtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"/>
</LinearLayout>
<TextView
android:id="#+id/checkStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="KIỂM TRA TÌNH TRẠNG XE"
android:textColor="#color/color_primary_green_dark"
android:textStyle="bold"
android:textSize="12dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/textView_item32"
android:layout_toEndOf="#+id/textView_item32"
android:layout_marginLeft="20dp"/>
</LinearLayout>
But when I load data for the first time, there is a redundant item. Look at the following attachment:
The exception has happened when updated code:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: pl.michalz.hideonscrollexample, PID: 9794
java.lang.ArrayIndexOutOfBoundsException: length=18; index=-1
at java.util.ArrayList.get(ArrayList.java:310)
at pl.michalz.hideonscrollexample.RecyclerViewAdapter$override.onBindViewHolder(RecyclerViewAdapter.java:54)
at pl.michalz.hideonscrollexample.RecyclerViewAdapter$override.access$dispatch(RecyclerViewAdapter.java)
at pl.michalz.hideonscrollexample.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:0)
at pl.michalz.hideonscrollexample.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:20)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5768)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5801)
How do I remove this redundant item in the CardView?
You have + 1 in your overridden getItemCount() method. It causes that you have one extra item in your list.
Then you have the method isPositionHeader, which you call in the onBindViewHolder method to find out, if the position is a header position. You are filling your cardview with data, if it is not the header position. But if it is the header position, you just skip it. So the first item, which is blank, is the header using the same cardview, as the other items, in fact.
Try to remove the + 1 and this condition if (!isPositionHeader(position)).

Click event not working for Recyclerview item with SwipeLayout in Xamarin Android

I setup a recyclerview with a viewholder with a click event on the recyclerview items, following the guide at https://developer.xamarin.com/guides/android/user_interface/recyclerview/
and everything worked just fine.
After that, i wanted to use this component for the swipe feature
https://components.xamarin.com/view/androidswipelayout
the swipe if working fine, but the click on the recyclerview item doens't trigger the event anymore. Any suggestions?
The itemlayout is
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<com.daimajia.swipe.SwipeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/swipe_layout"
android:clickable="false"
android:focusable="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF5534"
android:gravity="center_vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Elimina"
android:layout_marginLeft="30dp"
android:textColor="#fff"
android:textSize="17sp" />
<View
android:layout_height="wrap_content"
android:layout_width="0px"
android:layout_weight="1" />
<ImageView
android:id="#+id/trash"
android:layout_width="36dp"
android:layout_height="40dp"
android:layout_marginRight="50dp"
android:src="#drawable/trash" />
</LinearLayout>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="4dp"
app:cardUseCompatPadding="true"
app:cardCornerRadius="3dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:layout_width="100dp"
android:layout_height="150dp"
android:layout_margin="3dp"
android:id="#+id/imageView" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/title"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="5dp"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:lines="1"
android:maxLines="1"
android:ellipsize="end" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/author"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="5dp"
android:layout_marginBottom="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/fairNav"
android:id="#+id/progress"
android:layout_alignBottom="#+id/imageView"
android:layout_alignRight="#+id/imageView"
android:layout_gravity="bottom"
android:layout_margin="7dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</com.daimajia.swipe.SwipeLayout>
</FrameLayout>
the adapter:
public class BookCardAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler ItemClick;
List<LibraryEdition> items;
Context mContext {get; set;}
public BookCardAdapter(List<LibraryEdition> myDataset, Context context) {
items = myDataset;
mContext = context;
}
public override RecyclerView.ViewHolder OnCreateViewHolder (ViewGroup parent, int viewType)
{
// Inflate the CardView for the photo:
View itemView = LayoutInflater.From (parent.Context).
Inflate (Resource.Layout.CardBookListItem, parent, false);
BookCardViewHolder vh = new BookCardViewHolder (itemView, OnClick);
vh.Icon.Click += (object senerObj, EventArgs eve) => {
AndroidUtils.ReadList.Delete (items [vh.AdapterPosition].EditionID);
FairbooksAPI.DeleteFromReadingList (items [vh.AdapterPosition].VersionID);
items.RemoveAt (vh.AdapterPosition);
NotifyItemRemoved (vh.AdapterPosition);
NotifyItemRangeChanged (vh.AdapterPosition, items.Count);
vh.SwipeLayout.Close (true);
AndroidUtils.toUpdateHomeReadings = true;
};
vh.SwipeLayout.SetShowMode (SwipeLayout.ShowMode.LayDown);
vh.SwipeLayout.Opened += (sender, e) => {
YoYo.With (Techniques.Tada)
.Duration (700)
.PlayOn (vh.Icon);
};
return vh;
}
// Fill in the contents of the book (invoked by the layout manager):
public override void OnBindViewHolder (RecyclerView.ViewHolder holder, int position)
{
BookCardViewHolder vh = holder as BookCardViewHolder;
vh.Image.SetImageBitmap(null);
string coverUrl = items[position].CoverUrl;
AndroidUtils.SetImage (mContext, coverUrl, vh.Image);
vh.Title.Text = items[position].Title;
vh.Author.Text = "by " + items [position].Author.UserName;
int value = (int)items [position].Percentage;
vh.Progress.Text = value > 100 ? "100%" : value + "%";
}
// Return the number of books:
public override int ItemCount
{
get { return items.Count; }
}
// Raise an event when the item-click takes place:
void OnClick (int position)
{
if (ItemClick != null)
ItemClick (this, position);
}
}
the viewholder:
public class BookCardViewHolder : RecyclerView.ViewHolder
{
public SwipeLayout SwipeLayout;
public ImageView Icon;
public ImageView Image { get; private set; }
public TextView Title { get; private set; }
public TextView Author { get; private set; }
public TextView Progress { get; private set; }
public BookCardViewHolder (View itemView, Action<int> listener)
: base (itemView)
{
SwipeLayout = itemView.FindViewById<SwipeLayout> (Resource.Id.swipe_layout);
Icon = itemView.FindViewById<ImageView> (Resource.Id.trash);
Image = itemView.FindViewById<ImageView> (Resource.Id.imageView);
Title = itemView.FindViewById<TextView> (Resource.Id.title);
Author = itemView.FindViewById<TextView> (Resource.Id.author);
Progress = itemView.FindViewById<TextView> (Resource.Id.progress);
itemView.Click += (sender, e) => listener (base.AdapterPosition);
}
}
and in the parent fragment i set the adapter like this:
mAdapter = new BookCardAdapter (Books, this.Activity);
// Register the item click handler (below) with the adapter:
mAdapter.ItemClick += OnItemClick;
mRecyclerView.SetAdapter (mAdapter);
and:
void OnItemClick (object sender, int position)
{
// ProgressDialog progress = new ProgressDialog (this.Activity);
// progress.SetMessage ("Opening Book...");
// progress.Show ();
AndroidUtils.Read (Books [position], this.Activity);
}

RecyclerView strange behaviour inflating cells

I have this layout in two apps, one inside a RecyclerView and the other in a root activity layout.
Here the layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:orientation="vertical"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:background="#CFCFCF"
android:minHeight="250dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_red_dark"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_bright"
android:layout_above="#+id/commerceTextView"
>
<ImageView
android:src="#drawable/imagen"
android:id="#+id/commerceImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/commerceTextView"
android:gravity="center"
android:textStyle="bold"
android:textSize="24sp"
android:textColor="#F1F1F1"
android:background="#color/colorPrimary"
android:layout_alignParentBottom="true"
android:paddingTop="10dp"
android:text="Best food ever"
android:paddingBottom="10dp"/>
</RelativeLayout>
</FrameLayout>
Here the adapter
public class CommercesAdapter extends RecyclerView.Adapter<CommercesAdapter.CommercesViewHolder> {
private final Context context;
private final ImageLoader loader;
private List<CommerceEntity> commercesList;
#Inject
public CommercesAdapter(Context context, ImageLoader loader) {
this.context = context;
this.loader = loader;
}
public void setData(List<CommerceEntity> commercesList) {
this.commercesList = commercesList;
}
#Override
public CommercesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context)
.inflate(R.layout.list_comerces_item, parent, false);
return new CommercesViewHolder(view);
}
#Override
public void onBindViewHolder(CommercesViewHolder holder, int position) {
CommerceEntity commerce = commercesList.get(position);
String imageUri = commerce.getImageUri();
String name = commerce.getName();
// holder.commerceTypeName.setText(name);
//loader.bind(holder.commerceImage, imageUri);
}
#Override
public int getItemCount() {
return commercesList.size();
}
public static class CommercesViewHolder extends RecyclerView.ViewHolder {
public ImageView commerceImage;
public TextView commerceTypeName;
public CommercesViewHolder(View itemView) {
super(itemView);
commerceImage = (ImageView) itemView.findViewById(R.id.commerceImageView);
commerceTypeName = (TextView) itemView.findViewById(R.id.commerceTextView);
}
}
Here the RecyclerView
And here in a root activity layout
Someone knows why this happen? if I add android:centerInParent"true" to the nested FrameLayout the image appears but i don't understand why.
In your adapter, uncomment the two lines that you have commented out;
`
// holder.commerceTypeName.setText(name);
//loader.bind(holder.commerceImage, imageUri);
`

Categories

Resources