Tool bar is disappearing when applying recyclerviewer - android

I have this method when its called the toolbar is disappearing(the text of recycler is being on top of it), when i comment the method it the toolbar is visible.
can you help to the resolve it?
private void initViews() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
mydb = new DbHandler(this);
ArrayList<ListMainItem> listmainitem = mydb.getAllItemss("N");
ArrayList<ListMainItem> listmainitemheader = mydb.getAllItemss("Y");
MainItemsRCVAdapter mainitemadRCVapter = new MainItemsRCVAdapter(MainActivity.this, listmainitem, listmainitemheader);
recyclerView.setAdapter(mainitemadRCVapter);
}
this is the main activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v7.widget.RecyclerView
android:id="#+id/card_recycler_view"
android:scrollbars="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/app_bar_main"/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
this is mainitem header
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:background="#color/colorPrimaryDark"
android:layout_height="255dp">
<TextView
android:id="#+id/toptext"
android:layout_width="match_parent"
android:layout_height="35dp"
android:textSize="23dp"
android:text="New Games"
android:background="#color/colorAccent"
android:textColor="#color/colorText"
android:gravity="center"
android:layout_weight="0.7"
/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_horizontal"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="185dp"
android:layout_below="#+id/toptext"
android:paddingTop="8dp">
</android.support.v7.widget.RecyclerView>
<TextView
android:id="#+id/bottomtext"
android:layout_width="match_parent"
android:layout_height="35dp"
android:textSize="23dp"
android:text="Used Games"
android:layout_below="#+id/recycler_view_horizontal"
android:background="#color/colorAccent"
android:textColor="#color/colorText"
android:gravity="center" />
</RelativeLayout>
this is the Mainitemrecyclerview adapter
public class MainItemsRCVAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context mContext;
private ArrayList<ListMainItem> itemMain;
private ArrayList<ListMainItem> itemHeader;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
public MainItemsRCVAdapter( Context context ,ArrayList<ListMainItem> listMainItem ,ArrayList<ListMainItem> listMainItemHeader) {
setItemHeader(listMainItemHeader);
setItemMain(listMainItem);
mContext = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
//inflate your layout and pass it to view holder
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_item_adapter, parent, false);
MainItemsViewholder vh = new MainItemsViewholder(v, new MainItemsViewholder.IMyViewHolderClicks() {
public void onPotato(View caller) { Log.d("VEGETABLES", "Poh-tah-tos");
Intent intent = new Intent(mContext,SingleItemActivity.class);
mContext.startActivity(intent);
};
public void onTomato(ImageView callerImage) {
Log.d("VEGETABLES", "To-m8-tohs");
Intent intent = new Intent(mContext,SingleItemActivity.class);
mContext.startActivity(intent);
}
});
return new MyViewHolder(v);
} else if (viewType == TYPE_HEADER) {
//inflate your layout and pass it to view holder
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_item_header, parent, false);
return new MyViewHolderHeader(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof MyViewHolder) {
String name = getItemMain().get(position-1).geImgName();
Integer price = getItemMain().get(position-1).getPrice();
String convert_price = "Price: " + price.toString() + "$";
Log.d("###", "Setting name: " + name);
Log.d("###", "Setting URL " + name);
Log.d("###", "Setting price " + price + "p" + convert_price);
((MyViewHolder) holder).getmDataTextView().setText(name);
((MyViewHolder) holder).getmPriceTextView().setText(convert_price);
/* Picasso.with(mContext)
.load(R.drawable.img1)
.into(((MyViewHolder) holder).getmDataImageView());*/
Picasso.with(mContext)
.load(R.drawable.ww2)
.into(((MyViewHolder) holder).getmDataImageView());
} else if (holder instanceof MyViewHolderHeader) {
//cast holder to VHHeader and set data for header.
Log.d("####", "HEADER");
}
}
private class MyViewHolder extends RecyclerView.ViewHolder {
private TextView mDataTextView;
private TextView mPriceTextView;
private ImageView mDataImageView;
private RecyclerView mainViewRecyclerViewItems;
public MyViewHolder(View v) {
super(v);
/* mainViewRecyclerViewItems = (RecyclerView) v.findViewById(R.id.main_recycler_view);
MainItemsAdapter mAdapter = new MainItemsAdapter(getDataHorizontal(),mContext);
LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
mainViewRecyclerViewItems.setLayoutManager(layoutManager);
mainViewRecyclerViewItems.setAdapter(mAdapter);*/
mDataTextView = (TextView) v.findViewById(R.id.gamename_mg);
mPriceTextView=(TextView) v.findViewById(R.id.price_mg);
mDataImageView = (ImageView) v.findViewById(R.id.img_mg);
}
public TextView getmPriceTextView() {
return mPriceTextView;
}
public TextView getmDataTextView() {
return mDataTextView;
}
public ImageView getmDataImageView()
{
return mDataImageView;
}
}
private class MyViewHolderHeader extends RecyclerView.ViewHolder {
private final RecyclerView mHeaderRecyclerView;
public MyViewHolderHeader(View v) {
super(v);
mHeaderRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_view_horizontal);
HeaderItemsAdapter mAdapter = new HeaderItemsAdapter(getItemHeader(),mContext);
LinearLayoutManager layoutManager
= new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
mHeaderRecyclerView.setLayoutManager(layoutManager);
mHeaderRecyclerView.setAdapter(mAdapter);
}
}
#Override
public int getItemCount() {
return itemMain.size() + 1;
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position)) {
return TYPE_HEADER;
}
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
public void setItemMain(ArrayList<ListMainItem> itemmain) {
this.itemMain = itemmain;
}
public void setItemHeader(ArrayList<ListMainItem> itemheader) {
this.itemHeader = itemheader;
}
public ArrayList<ListMainItem> getItemHeader() {
return itemHeader;
}
public ArrayList<ListMainItem> getItemMain() {
return itemMain;
}
}
edit:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<!-- <include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />-->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.v7.widget.RecyclerView
android:id="#+id/card_recycler_view"
android:scrollbars="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"/>
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>

The way DrawerLayout works - inside it you'll define two layouts. The first one will be used as your main content, the second one is the content of the drawer.
When you declare a frame layout as your content and put the toolbar and the recycler view in there, they overlap (same thing would happen even without the drawer). From Android documentation on FrameLayout: "Child views are drawn in a stack, with the most recently added child on top."
Replace your FrameLayout with RelativeLayout (you even have android:layout_below="#+id/toolbar" already) or LinearLayout and it should work.

Related

Unable to Align 2 Cardviews Vertically Inside RecyclerView

I have 2 CardViews and a RecyclerView but i am
unable to align them vertically
unable to slide them independently (both slide if I slide any one in a bugged workaround)
I tried a few workarounds as well as different tutorials like edmt Dev and CodingWithMitch as well as searched for similar problems on stackoverflow but the problem seems to persist. So how do I align both of the cardviews vertically while still being able to slide each of them independently and horizontally.
(Code works fine for single card view)
Main Activity:
public class MainActivity extends AppCompatActivity {
List<Articles> articlesData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
articlesData = new ArrayList<>();
//Repeats
articlesData.add(new Articles("10 Necessary Gadgets","Gadgets","Gadgets You Must Carry",R.drawable.bagchaincustom));
articlesData.add(new Articles("10 Benefits of Pre-Planning the Day","Self Improvement","Benefits of Planning in Advance",R.drawable.planner1custom));
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, articlesData);
recyclerView.setAdapter(adapter);
}
Here is 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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerview"
android:orientation="horizontal">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the RecyclerViewAdapter Class:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int LAYOUT_ONE= 0;
private static final int LAYOUT_TWO= 1;
#Override
public int getItemViewType(int position)
{
if(position == LAYOUT_ONE){
return LAYOUT_TWO;
}
else {
return LAYOUT_ONE;
}
}
private static final String Tag = "RecyclerViewAdapter";
private Context mContext;
private List<Articles> mData;
public RecyclerViewAdapter(Context mContext, List<Articles> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater mInflater = LayoutInflater.from(mContext);
View view;
switch (viewType) {
case 0:
ViewHolder1 viewHolder1;
view = mInflater.inflate(R.layout.layout_listitem, parent, false);
return new ViewHolder1(view);
case 1:
ViewHolder2 viewHolder2;
view = mInflater.inflate(R.layout.layout_listitem2, parent, false);
return new ViewHolder2(view);
default:
return null;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, final int position) {
switch (holder.getItemViewType()){
case 0:
ViewHolder1 viewHolder1 = (ViewHolder1)holder;
viewHolder1.tv_article_title.setText(mData.get(position).getTitle());
viewHolder1.img_article_thumbnail.setImageResource(mData.get(position).getThumbnail());
viewHolder1.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ArticlesActivity.class);
intent.putExtra("Title", mData.get(position).getTitle());
intent.putExtra("Description", mData.get(position).getDescription());
intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
intent.putExtra("Category", mData.get(position).getCategory());
mContext.startActivity(intent);
}
});
break;
case 1:
ViewHolder2 viewHolder2 = (ViewHolder2)holder;
viewHolder2.tv_article_title2.setText(mData.get(position).getTitle());
viewHolder2.img_article_thumbnail2.setImageResource(mData.get(position).getThumbnail());
viewHolder2.cardView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ArticlesActivity.class);
intent.putExtra("Title", mData.get(position).getTitle());
intent.putExtra("Description", mData.get(position).getDescription());
intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
intent.putExtra("Category", mData.get(position).getCategory());
mContext.startActivity(intent);
}
});
break;
}
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder1 extends RecyclerView.ViewHolder{
TextView tv_article_title;
ImageView img_article_thumbnail;
CardView cardView;
public ViewHolder1(#NonNull View itemView) {
super(itemView);
tv_article_title = (TextView) itemView.findViewById(R.id.article_title_id);
img_article_thumbnail = (ImageView) itemView.findViewById((R.id.article_image_id));
cardView = (CardView) itemView.findViewById(R.id.cardview_id);
}
}
public class ViewHolder2 extends RecyclerView.ViewHolder{
TextView tv_article_title2;
ImageView img_article_thumbnail2;
CardView cardView2;
public ViewHolder2(#NonNull View itemView) {
super(itemView);
tv_article_title2 = (TextView) itemView.findViewById(R.id.article_title_id2);
img_article_thumbnail2 = (ImageView) itemView.findViewById((R.id.article_image_id2));
cardView2 = (CardView) itemView.findViewById(R.id.cardview_id2);
}
}
}
Here is the Articles Class:
public class Articles {
private String Title;
private String Category;
private String Description;
private int Thumbnail;
public Articles(String title, String category, String description, int thumbnail) {
Title = title;
Category = category;
Description = description;
Thumbnail = thumbnail;
}
public String getTitle() {
return Title;
}
public String getCategory() {
return Category;
}
public String getDescription() {
return Description;
}
public int getThumbnail() {
return Thumbnail;
}
And here is the CardView -> layout_listitem Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:layout_alignParentStart="true"
android:id="#+id/rview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:id="#+id/cardview_id"
android:layout_width="120dp"
android:layout_height="220dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="0dp"
app:cardElevation="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">
<ImageView
android:id="#+id/article_image_id"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="#2d2d2d"
android:scaleType="centerCrop"></ImageView>
<TextView
android:id="#+id/article_title_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Article Name"
android:textSize="14sp">
</TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
And here is the CardView -> layout_listitem2 Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:layout_alignParentStart="true"
android:id="#+id/rview2"
android:layout_below="#+id/rview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="300dp">
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:id="#+id/cardview_id2"
android:layout_below="#id/cardview_id"
android:layout_width="120dp"
android:layout_height="220dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="0dp"
app:cardElevation="0dp">
<LinearLayout
android:layout_marginTop="250dp"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">
<ImageView
android:id="#+id/article_image_id2"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="#2d2d2d"
android:scaleType="centerCrop"></ImageView>
<TextView
android:id="#+id/article_title_id2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Article Name Sec"
android:textSize="14sp">
</TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
ConstraintLayout is not a scrolling parent, so it will create problem if you add a long RecyclerView inside it.
So I made a few modifications to the above code and it has solved the both problems (Independent sliding and vertical alignment)
I have added another recyclerview in main_activity.xml
<LinearLayout 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=".MainActivity"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</androidx.recyclerview.widget.RecyclerView>
<androidx.recyclerview.widget.RecyclerView
android:layout_below="#+id/recyclerview_id2"
android:layout_marginTop="10dp"
android:id="#+id/recyclerview_id2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="NotSibling">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
I have also created another Adapter for the new recyclerview, seperated classes for both viewholders as well as removed the switch statements and itemViewType from RecyclerViewAdapter and RecyclerViewAdapter2 class :
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater mInflater = LayoutInflater.from(mContext);
view = mInflater.inflate(R.layout.layout_listitem2,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.tv_article_title2.setText(mData.get(position).getTitle());
holder.img_article_thumbnail2.setImageResource(mData.get(position).getThumbnail());
holder.cardView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext,ArticlesActivity.class);
intent.putExtra("Title",mData.get(position).getTitle());
intent.putExtra("Description",mData.get(position).getDescription());
intent.putExtra("Thumbnail",mData.get(position).getThumbnail());
intent.putExtra("Category",mData.get(position).getCategory());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView tv_article_title2;
ImageView img_article_thumbnail2;
CardView cardView2;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tv_article_title2 = (TextView) itemView.findViewById(R.id.article_title_id2);
img_article_thumbnail2 = (ImageView) itemView.findViewById((R.id.article_image_id2));
cardView2 = (CardView) itemView.findViewById(R.id.cardview_id2);
}
}
I also edited the main_acitivty class by adding the new recyclerview and layout manager at the end:
LinearLayoutManager layoutManager2 = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
RecyclerView recyclerView2 = findViewById(R.id.recyclerview_id2);
recyclerView2.setLayoutManager(layoutManager2);
RecyclerViewAdapter2 adapter2 = new RecyclerViewAdapter2(this, articlesData);
recyclerView2.setAdapter(adapter2);
Even though this workaround fixes both problems i was facing is there any other better/more refined way of doing this (eg by using single recyclerview) and where did i made the mistake in previous approach?

CardView not displaying within RecyclerView

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));

RecyclerVIew is not recycling CardView containing images and text inside NestedScrollView

I am using 3 recyclerView inside a nestedScrolView, first 2 are GridView and the 3rd one is LinearLayout.
Now as I am scrolling through few items 3rd recycler view shows laggy behavior, and I have a hunch that items are not recycled.
And I think that it's also affecting(laggy behavior) my Navigation Drawer(opening and closing)
Below is my code
#Override
protected void onPostExecute(Void aVoid) {
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
recyclerView = (RecyclerView) view.findViewById(R.id.feeds_recyclerView);
recyclerView.setNestedScrollingEnabled(false);
mLayoutManager = new LinearLayoutManager(getContext());
load = new FeedAdapter(getActivity(), worldpopulationlist);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(load);
progressBar.setVisibility(View.GONE);
viewMore.setVisibility(View.VISIBLE);
viewMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new LoadMoreDataTask().execute();
}
});
}
NestedScrollView XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="#color/turquoise"
app:layout_scrollFlags="scroll|snap|exitUntilCollapsed"
app:scrimVisibleHeightTrigger="180dp">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="?attr/actionBarSize"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/turquoise"
app:layout_collapseMode="pin" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/light_grey"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:id="#+id/mainContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</FrameLayout>
<FrameLayout
android:id="#+id/mainContainer2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
</FrameLayout>
<FrameLayout
android:id="#+id/mainContainer3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
</FrameLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
Inflated Single Row Xml
<FrameLayout 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="Fragment.Feeds">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/feeds"
android:textColor="#color/turquoise"
android:textSize="20sp"
android:textStyle="bold" />
<ImageView
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:background="#color/grey" />
<android.support.v7.widget.RecyclerView
android:id="#+id/feeds_recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</android.support.v7.widget.RecyclerView>
<TextView
android:id="#+id/view_more"
style="#style/Base.TextAppearance.AppCompat.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:text="View More"
android:textColor="#color/turquoise" />
<ProgressBar
android:id="#+id/progressBar"
style="#style/Widget.AppCompat.ProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
3rd Adapter
public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.MyViewHolder> {
View itemView;
private View nativeExpressLayoutView;
private View itemView1;
private Context context;
private List<WorldPopulation> worldpopulationlist = null;
private WorldPopulation movie;
private int x;
private AdRequest adRequest = new AdRequest.Builder()
.build();
public FeedAdapter(FragmentActivity feeds, List<WorldPopulation> worldpopulationlist) {
this.context = feeds;
this.worldpopulationlist = worldpopulationlist;
ArrayList<WorldPopulation> arraylist = new ArrayList<>();
arraylist.addAll(worldpopulationlist);
}
#Override
public int getItemViewType(int position) {
movie = worldpopulationlist.get(position);
if (movie.getAds() == 1) {
return 1;
} else if (movie.getAds()==0){
return 0;
} else if(movie.getAds()==2){
return 2 ;
}
return 1;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 1:
itemView1 = LayoutInflater.from(parent.getContext())
.inflate(R.layout.feeds_adv_single_row, parent, false);
return new MyViewHolder(itemView1);
case 0:
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.feeds_single_row, parent, false);
return new MyViewHolder(itemView);
case 2:
nativeExpressLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.ad_view_type, parent, false);
return new MyViewHolder(nativeExpressLayoutView);
}
return null;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
movie = worldpopulationlist.get(holder.getAdapterPosition());
if (holder.mview == itemView1) {
holder.brandImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent x = new Intent(context, Full_Image.class);
x.putExtra("image",worldpopulationlist.get(position).getBrand_Image());
context.startActivity(x);
}
});
holder.mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AdsActivity.class);
intent.putExtra("adsNext", worldpopulationlist.get(position).getAdsSecond());
intent.putExtra("objId", worldpopulationlist.get(position).getObjectId());
intent.putExtra("brandImage", worldpopulationlist.get(position).getBrand_Image());
intent.putExtra("brandName", worldpopulationlist.get(position).getAuthor_Name());
intent.putExtra("link", worldpopulationlist.get(position).getLink());
intent.putExtra("mobNo", worldpopulationlist.get(position).getCall());
intent.putExtra("brandDescription", worldpopulationlist.get(position).getPages());
intent.putExtra("brandDescriptionText", worldpopulationlist.get(position).getPage_No());
intent.putExtra("contactUs", worldpopulationlist.get(position).getContactUs());
intent.putExtra("aboutUs", worldpopulationlist.get(position).getAboutUs());
context.startActivity(intent);
}
});
} else if (holder.mview == itemView) {
holder.mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, Feeds_Second.class);
intent.putExtra("rank", worldpopulationlist.get(position).getImagesContent());
intent.putExtra("image", worldpopulationlist.get(position).getFlag());
intent.putExtra("ads", worldpopulationlist.get(position).getAds());
intent.putExtra("call", worldpopulationlist.get(position).getCall());
intent.putExtra("objectId", worldpopulationlist.get(position).getObjectId());
intent.putExtra("contactUs", worldpopulationlist.get(position).getContactUs());
intent.putExtra("aboutUs", worldpopulationlist.get(position).getAboutUs());
intent.putExtra("switch", worldpopulationlist.get(position).getSwitches());
intent.putExtra("link", worldpopulationlist.get(position).getLink());
intent.putExtra("clicks", worldpopulationlist.get(position).getClicks());
context.startActivity(intent);
}
});
}
x = movie.getAds();
if (x == 1) {
holder.brandName.setText(movie.getAuthor_Name());
holder.brandDescription.setText(movie.getPages()); // when setting brandDescription to the objectId it shows objectId ysZicAeoRU
holder.brandDescriptionText.setText(movie.getPage_No());
Picasso.with(context)
.load(worldpopulationlist.get(position).getBrand_Image())
.placeholder(R.drawable.place_holder)
.error(R.drawable.broken_image)
.into(holder.brandImage);
Picasso.with(context)
.load(worldpopulationlist.get(position).getFlag())
.placeholder(R.drawable.place_holder)
.error(R.drawable.broken_image)
.into(holder.brandMainImage);
} else if (x==0){
holder.imageContent.setText(movie.getImagesContent());
holder.userName.setText(movie.getAddress());
holder.author.setText(movie.getAuthor());
holder.authorName.setText(movie.getAuthor_Name());
holder.pages.setText(movie.getPages());
holder.pageNo.setText(String.valueOf(movie.getClicks()));
holder.userImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent y = new Intent(context, WrapImage.class);
y.putExtra("image",worldpopulationlist.get(position).getUserImage());
context.startActivity(y);
}
});
Picasso.with(context)
.load(worldpopulationlist.get(position).getUserImage())
.placeholder(R.drawable.place_holder)
.error(R.drawable.broken_image)
.into(holder.userImage);
Picasso.with(context)
.load(worldpopulationlist.get(position).getFlag())
.placeholder(R.drawable.place_holder)
.error(R.drawable.broken_image)
.into(holder.feedsImage);
} else if (x ==2){
holder.adView.loadAd(adRequest);
}
}
#Override
public int getItemCount() {
return worldpopulationlist.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView imageContent, userName, author, authorName, pages, pageNo;
TextView brandName, brandDescription, brandDescriptionText;
ImageView feedsImage, brandImage, brandMainImage, userImage;
View mview;
AdView adView;
public MyViewHolder(View v) {
super(v);
mview = v;
imageContent = (TextView) v.findViewById(R.id.recycler_text);
feedsImage = (ImageView) v.findViewById(R.id.flag);
userImage = (ImageView) v.findViewById(R.id.userImage);
userName = (TextView) v.findViewById(R.id.userName);
author = (TextView) v.findViewById(R.id.author);
authorName = (TextView) v.findViewById(R.id.author_name);
pages = (TextView) v.findViewById(R.id.pages);
pageNo = (TextView) v.findViewById(R.id.page_no);
brandName = (TextView) v.findViewById(R.id.brand_name);
brandDescription = (TextView) v.findViewById(R.id.author_brand_description);
brandDescriptionText = (TextView) v.findViewById(R.id.author_name_brand_description);
brandImage = (ImageView) v.findViewById(R.id.brand_image);
brandMainImage = (ImageView) v.findViewById(R.id.brand_main_image);
adView = (AdView)v. findViewById(R.id.adView);
}
}
}

RecyclerView 2 Columns with CardView

I have a problem with my layout. I'm trying to do something like this:
For now, i have a RecyclerView with a CardView inside it. in the CardView I have put an ImageView and a TextView but I don't know why but the CardView is more height than ImageView inside it.
Here is The code and a Sample Image.
And Here is the code: Activity
public class AddRoomActivity extends AppCompatActivity implements View.OnClickListener {
private View snackView;
private FloatingActionButton fabDoneAddRoom;
private EditText etRoomName;
private String roomName = null;
public final static String KEY_PI_IP = "MyPi_IP";
private final static String KEY_ROOM = "myRoom";
private final static String KEY_ROOM_TYPE = "myRoom_Type";
private RecyclerView typeRecyclerView;
private GridLayoutManager layoutManager;
private AddRoomActivity.TypeAdapter adapter;
private String myPi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_room);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fabDoneAddRoom = (FloatingActionButton) findViewById(R.id.doneAddRoom);
fabDoneAddRoom.setOnClickListener(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
etRoomName = (EditText) findViewById(R.id.addRoomName);
myPi = getIntent().getStringExtra(KEY_PI_IP);
layoutManager = new GridLayoutManager(this, 2);
typeRecyclerView = (RecyclerView) findViewById(R.id.recyclerTypeRoom);
typeRecyclerView.setHasFixedSize(true);
typeRecyclerView.setLayoutManager(layoutManager);
// specify an adapter (see also next example)
adapter = new TypeAdapter(getResources().getStringArray(R.array.roomTypeName));
typeRecyclerView.setAdapter(adapter);
}
void showToastMessage(String message) {
Snackbar.make(snackView, message, Snackbar.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.doneAddRoom) {
snackView = v;
String myString = etRoomName.getText().toString();
if (myString.length() > 0) {
roomName = myString.substring(0, 1).toUpperCase() + myString.substring(1);
addRoomToPi();
} else {
showToastMessage(getString(R.string.noNameRoom));
}
}
}
private void addRoomToPi() {
Integer ret = -1;
try {
ret = (Integer) new RaspberryTCPClient(myPi, getResources(), RaspberryTCPClient.TYPE_ADD_ROOM, roomName, XMLRoom.TYPE_KITCHEN_ROOM).execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (ret == RaspberryTCPClient.OPERATION_DONE) {
showToastMessage(getString(R.string.roomAdded));
Intent data = new Intent();
data.putExtra(KEY_ROOM, roomName);
setResult(Activity.RESULT_OK, data);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, 1500);
} else {
showToastMessage(getString(R.string.addRoomError));
}
}
private class TypeAdapter extends RecyclerView.Adapter<AddRoomActivity.TypeAdapter.ViewHolder> {
private String[] myData;
public TypeAdapter(String[] roomList) {
myData = roomList;
}
public void onItemClick(int position) {
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView tvType;
public CardView cvRoomCard;
public ImageView imgRoomType;
public ViewHolder(View vCard) {
super(vCard);
cvRoomCard = (CardView) vCard;
tvType = (TextView) vCard.findViewById(R.id.tvTypeName);
imgRoomType = (ImageView) vCard.findViewById(R.id.img_roomType);
}
}
#Override
public AddRoomActivity.TypeAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.type_room_recycler_view, parent, false);
// set the view's size, margins, paddings and layout parameters
//...
AddRoomActivity.TypeAdapter.ViewHolder vh = new AddRoomActivity.TypeAdapter.ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(AddRoomActivity.TypeAdapter.ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.tvType.setText(myData[position]);
switch (position) {
case XMLRoom.TYPE_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_room_sqr);
break;
case XMLRoom.TYPE_BED_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_bedroom_sqr);
break;
case XMLRoom.TYPE_GARDEN_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_garden_sqr);
break;
case XMLRoom.TYPE_KITCHEN_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_kitchen_sqr);
break;
case XMLRoom.TYPE_LIVING_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_living_room_sqr);
break;
case XMLRoom.TYPE_SWIMMING_POOL_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_swimming_pool_sqr);
break;
}
holder.cvRoomCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClick(position);
}
});
}
#Override
public int getItemCount() {
return myData.length;
}
}
The MainLayout
<android.support.design.widget.AppBarLayout
android:id="#+id/appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="#dimen/toolbar"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="90dp"
android:layout_marginTop="#dimen/toolbar"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true">
<TextView
android:id="#+id/tvAddRoom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_margin="5dp"
android:gravity="center"
android:text="#string/textAddRoom"
android:textColor="#color/primary_text"
android:textSize="20dp"
android:textStyle="bold" />
<android.support.design.widget.TextInputLayout
android:id="#+id/inputaddRoomName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tvAddRoom"
android:layout_gravity="center"
android:layout_margin="5dp">
<EditText
android:id="#+id/addRoomName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_RoomName"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerTypeRoom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/inputaddRoomName"
android:scrollbars="vertical" />
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/doneAddRoom"
android:layout_width="#dimen/fab_Dimension"
android:layout_height="#dimen/fab_Dimension"
android:layout_gravity="bottom|center"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#drawable/ic_done" />
</android.support.design.widget.CoordinatorLayout>
and The View Layout:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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="4dp">
<ImageView
android:id="#+id/img_roomType"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:src="#drawable/img_room" />
<TextView
android:id="#+id/tvTypeName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center"
android:textColor="#android:color/white"
android:textSize="20sp" />
</android.support.v7.widget.CardView>
Extracted required info from the accepted answer in case URL becomes invalid in future and to save time.
GridLayoutManager is used to display the RecyclerView in Grid manner instead of list.
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(mLayoutManager);
Kotlin version:
recyclerView.apply {
layoutManager = GridLayoutManager(this, 2)
}
You can use this code simply
<android.support.v7.widget.RecyclerView
app:layoutManager="android.support.v7.widget.GridLayoutManager"
app:spanCount="2"/>
With androidX libraries simply do:
<androidx.recyclerview.widget.RecyclerView
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"/>
for Horizontal recycler view, it works for me
layoutManagerSuperCategories = new GridLayoutManager(context,2,LinearLayoutManager.HORIZONTAL,false);
rv_superCategories.setLayoutManager(layoutManagerSuperCategories);
use "0dp" in layout_width and layout_height for putting views in it's position.
like this:
android:layout_width="0dp"
and use Guidelines in your xml.
<ImageView
android:id="#+id/img_roomType"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentTop="true"
android:src="#drawable/img_room" />
<TextView
android:id="#+id/tvTypeName"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="bottom"
android:gravity="center"
android:textColor="#android:color/white"
android:textSize="20sp" />
this is NOT true code, u have to use Guidelines.

How to start different activities on click of different recycler views

I have a RecyclerView with GridLayoutManager. On click of each Item i want tstart different acticities. I have tried but it is not working. This is my DashboardAdapter class
public class DashboardAdapter extends RecyclerView.Adapter<DashboardAdapter.ViewHolder>{
private List<DashboardPojo> countries;
private int rowLayout;
private Context mContext;
public DashboardAdapter(List<DashboardPojo> countries, int rowLayout, Context context) {
this.countries = countries;
this.rowLayout = rowLayout;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
DashboardPojo country = countries.get(i);
viewHolder.countryName.setText(country.name);
viewHolder.countryImage.setImageResource(country.getImageResourceId(mContext));
}
#Override
public int getItemCount() {
return countries == null ? 0 : countries.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView countryName;
public ImageView countryImage;
public ViewHolder(View itemView) {
super(itemView);
mContext = itemView.getContext();
itemView.setOnClickListener(this);
countryName = (TextView) itemView.findViewById(R.id.countryName);
countryImage = (ImageView)itemView.findViewById(R.id.countryImage);
}
#Override
public void onClick(View v) {
final Intent intent;
if (getPosition() == 0){
intent = new Intent(mContext, TutorialActivity.class);
} else if (getPosition() == 1){
intent = new Intent(mContext, JobsActivity.class);
} else {
intent = new Intent(mContext, TutorialActivity.class);
}
mContext.startActivity(intent);
}
}
}
And in my DashBoardActivity i have
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter = new DashboardAdapter(DashboardManager.getInstance().getCountries(), R.layout.dashboard_row, this);
mRecyclerView.setAdapter(mAdapter);
And is dashboard_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_margin="5dp"
card_view:cardCornerRadius="5dp"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/countryImage"
android:layout_width="match_parent"
android:layout_height="120dp"
android:scaleType="centerCrop"
android:tint="#color/photo_tint"
android:layout_centerInParent="true"
/>
<TextView
android:id="#+id/countryName"
android:gravity="center"
android:background="?android:selectableItemBackground"
android:focusable="true"
android:clickable="true"
android:layout_width="match_parent"
android:layout_height="100dp"
android:textSize="24sp"
android:layout_centerInParent="true"
android:textColor="#android:color/white"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
activity_dashboard.xml
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/rel"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DashBoardActivity"
android:layout_below="#+id/app_bar"
android:layout_marginTop="20dp"/>
</RelativeLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="solutions.techieweb.com.techiewebsolutions.NavigationDrawerFragment"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
Please help me....
From what u have posted it seems that your View onClick() event is consumed by TextView
Please remove the :
android:focusable="true"
android:clickable="true"
tag from countryname TextView
And also change getPosition() to getAdapterPosition() as getPosition() is deprecated
Try This:
v.getContext().startActivity(intent);
Instead of:
mContext.startActivity(intent);

Categories

Resources