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.
Related
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.
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.
I am not getting any view from the recycler, I did some debug and the constructor of the adapter is called with items on its list, also the method
getItemCount()
but none of the rest seem to be executed.
I´ve been wandering around stack looking for this problem and i found different approaches to a solution, problem is none worked out for me, maybe I am just missing something i can´t see.
I read somewhere that it could be because the recycler view is inside an scroll view, but the solution given did not worked for me
my custom adapter:
public class CircumstancesAdapter extends RecyclerView.Adapter<CircumstancesAdapter.CircumstancesViewHolder> {
List<CatalogRespModel> circumList;
Context mContext;
public CircumstancesAdapter(List<CatalogRespModel> list, Context context) {
this.circumList = list;
this.mContext = context;
}
#Override
public CircumstancesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.row_item_circumstances, parent, false);
return new CircumstancesViewHolder(view);
}
#Override
public void onBindViewHolder(CircumstancesViewHolder holder, int position) {
holder.tvCircum.setText(circumList.get(position).get_Descripcion());
}
#Override
public int getItemCount() {
if(circumList != null) return circumList.size();
else return 0;
}
public class CircumstancesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
RadioButton rbCircum;
TextView tvCircum;
private Context context;
public CircumstancesViewHolder(View itemView) {
super(itemView);
rbCircum = (RadioButton) itemView.findViewById(R.id.rb_circ);
rbCircum.setOnClickListener(this);
tvCircum = (TextView) itemView.findViewById(R.id.tv_circ);
this.context = itemView.getContext();
}
#Override
public void onClick(View v) {
}
}
}
my container layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:id="#+id/text2"
android:text="#string/text_circ"
android:textSize="20sp"
android:textColor="#color/colorPrimaryshadow"/>
<RelativeLayout
android:id="#+id/placa"
android:layout_width="180dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:background="#drawable/placa">
<TextView
android:id="#+id/tv_plate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:layout_centerInParent="true"
android:text="#string/dummy"
android:textSize="40sp"
android:textColor="#android:color/black"/>
</RelativeLayout>
<ImageView
android:id="#+id/iv_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="true"
android:src="#drawable/conductora" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rview_circumstances"
android:layout_width="match_parent"
android:background="#fff"
android:orientation="vertical"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/boton_continuar_circustanciasa"
android:layout_marginTop="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/continuar"
android:layout_marginBottom="10dp"
android:elevation="30dp"
android:layout_gravity="center"/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</FrameLayout>
my row layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:background="#fff"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/rb_circ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#color/colorAccentDark"
android:gravity="center_vertical"
android:textSize="14sp" />
<TextView
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:id="#+id/tv_circ"
android:textSize="14sp"
android:text="texto de prueba"
android:textColor="#color/colorAccentDark"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
and in my onCreateView inside the fragment:
recyclerView = (RecyclerView) rootView.findViewById(R.id.rview_circumstances);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
if(Catalogs.circumstancesArray.size() > 0){
adapter = new CircumstancesAdapter(Catalogs.circumstancesArray, getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
}
Note: I checked the List size and is greater than 0
Fragment code as requested:
public class CircumstancesFragment extends Fragment {
Button btnContinue;
TextView tvPlate;
private ImageView ivIndicator;
private static int iNumDevices;
IFragmentListener iFragmentListener;
private RecyclerView recyclerView;
RecyclerView.Adapter adapter;
private final static String TAGMap = CircumstancesFragment.class.getSimpleName();
public static final String TAG = "CircumstancesFragment.java";
public static CircumstancesFragment getInstance(Bundle bundle){
if(bundle != null){
iNumDevices = bundle.getInt("numDevices");
}
return new CircumstancesFragment();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context != null){
if(context instanceof IFragmentListener){
iFragmentListener = (IFragmentListener) context;
} else
throw new RuntimeException("el contexto no esta implementando la interfaz");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_circustancias_, container, false);
btnContinue = (Button) rootView.findViewById(R.id.boton_continuar_circustanciasa);
tvPlate = (TextView) rootView.findViewById(R.id.tv_plate);
recyclerView = (RecyclerView) rootView.findViewById(R.id.rview_circumstances);
ivIndicator = (ImageView) rootView.findViewById(R.id.iv_indicator);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
if(Catalogs.circumstancesArray.size() > 0){
adapter = new CircumstancesAdapter(Catalogs.circumstancesArray, getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
btnContinue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
try
{
iFragmentListener.notify(null, TAG);
} catch (Exception ex)
{
Log.d("error", ex.getMessage());
}
}
});
setLayout(iNumDevices);
return rootView;
}
private void setLayout(int i){
tvPlate.setText(FdccoreConstants.insuredArray.get(0).get_Placa_Vehiculo());
if(i== FdccoreConstants.ONE_DEVICE){
ivIndicator.setImageResource(R.drawable.conductora);
}else if(i== FdccoreConstants.TWO_DEVICE){
ivIndicator.setImageResource(R.drawable.only_conductor);
}
}
private void resetView(){
}
}
Please provide more code because Your layout and adapter is working fine.
I only changed Your model list to String.
Maybe in place when You checked list size and list.size() > 0 add
adapter.notifyDataSetChanged();
=====
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rview_circumstances);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
list = new ArrayList<>();
list.add("asd");
list.add("sasf");
list.add("asasfasf");
list.add("asgagsad");
list.add("asgas");
list.add("asagasgd");
list.add("asreyeryd");
list.add("asgsheyd");
CircumstancesAdapter adapter = new CircumstancesAdapter(list, this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
solution: somehow in order to work with the scroll view i must add this line
compile 'com.android.support:recyclerview-v7:25.3.1'
compiling only appcompat-v7 wont work
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));
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);
}
}
}