I have multiple checkboxes (switches in my case), in a nested recycler view. It looks like the following :
I want to be able to retrieve all switch states on this screen when the user goes back and be able to identify which one’s are set to true. For example, I’m looking to obtain something in a similar format to this:
[Item 0, Sub Item 1, TRUE], [Item 0, Sub Item 2, TRUE], [Item 1, Sub Item 0, TRUE] , etc.
My issue is that I’m not exactly sure how to store these switch states. I'm not sure how to get the specific switch values here when they're placed in a nested recycler view.
Here is the code I'm following:
MainActivity
package com.example.recycledviewpoolexample;
import android.nfc.Tag;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView rvItem = findViewById(R.id.rv_item);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
ItemAdapter itemAdapter = new ItemAdapter(buildItemList());
rvItem.setAdapter(itemAdapter);
rvItem.setLayoutManager(layoutManager);
}
private List<Item> buildItemList() {
List<Item> itemList = new ArrayList<>();
for (int i=0; i<10; i++) {
Item item = new Item("Item "+i, buildSubItemList());
itemList.add(item);
}
return itemList;
}
private List<SubItem> buildSubItemList() {
List<SubItem> subItemList = new ArrayList<>();
for (int i=0; i<3; i++) {
SubItem subItem = new SubItem("Sub Item "+i, false);
subItemList.add(subItem);
}
return subItemList;
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
/*if Checkboxes are true, store/display them in the logs
EXAMPLE OUTPUT:
Item (String)
SubItem (String)
*/
}
}
Item.java
public class Item {
private String itemTitle;
private List<SubItem> subItemList;
public Item(String itemTitle, List<SubItem> subItemList) {
this.itemTitle = itemTitle;
this.subItemList = subItemList;
}
public String getItemTitle() {
return itemTitle;
}
public void setItemTitle(String itemTitle) {
this.itemTitle = itemTitle;
}
public List<SubItem> getSubItemList() {
return subItemList;
}
public void setSubItemList(List<SubItem> subItemList) {
this.subItemList = subItemList;
}
}
ItemAdapter
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder> {
private RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
private List<Item> itemList;
ItemAdapter(List<Item> itemList) {
this.itemList = itemList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_item, viewGroup, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder itemViewHolder, int i) {
Item item = itemList.get(i);
itemViewHolder.tvItemTitle.setText(item.getItemTitle());
// Create layout manager with initial prefetch item count
LinearLayoutManager layoutManager = new LinearLayoutManager(
itemViewHolder.rvSubItem.getContext(),
LinearLayoutManager.VERTICAL,
false
);
layoutManager.setInitialPrefetchItemCount(item.getSubItemList().size());
// Create sub item view adapter
SubItemAdapter subItemAdapter = new SubItemAdapter(item.getSubItemList());
itemViewHolder.rvSubItem.setLayoutManager(layoutManager);
itemViewHolder.rvSubItem.setAdapter(subItemAdapter);
itemViewHolder.rvSubItem.setRecycledViewPool(viewPool);
}
#Override
public int getItemCount() {
return itemList.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView tvItemTitle;
private RecyclerView rvSubItem;
ItemViewHolder(View itemView) {
super(itemView);
tvItemTitle = itemView.findViewById(R.id.tv_item_title);
rvSubItem = itemView.findViewById(R.id.rv_sub_item);
}
}
}
SubItem.java
package com.example.recycledviewpoolexample;
public class SubItem {
private int subItemImage;
private String subItemTitle;
private boolean checkbox;
public SubItem(String subItemTitle, boolean checkbox) {
this.subItemTitle = subItemTitle;
this.checkbox = checkbox;
}
public int getSubItemImage() {
return subItemImage;
}
public void setSubItemImage(int subItemImage) {
this.subItemImage = subItemImage;
}
public String getSubItemTitle() {
return subItemTitle;
}
public void setSubItemTitle(String subItemTitle) {
this.subItemTitle = subItemTitle;
}
public boolean isSelected() {
return checkbox;
}
public void setCheckbox(boolean checkbox) {
this.checkbox = checkbox;
}
}
SubItemAdapter.java
public class SubItemAdapter extends RecyclerView.Adapter<SubItemAdapter.SubItemViewHolder> {
private List<SubItem> subItemList;
SubItemAdapter(List<SubItem> subItemList) {
this.subItemList = subItemList;
}
#NonNull
#Override
public SubItemViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_sub_item, viewGroup, false);
return new SubItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SubItemViewHolder subItemViewHolder, int i) {
final SubItem subItem = subItemList.get(i);
subItemViewHolder.tvSubItemTitle.setText(subItem.getSubItemTitle());
subItemViewHolder.checkBox.setOnCheckedChangeListener(null);
subItemViewHolder.checkBox.setChecked(subItem.isSelected());
subItemViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
subItem.setCheckbox(isChecked);
}
});
}
#Override
public int getItemCount() {
return subItemList.size();
}
class SubItemViewHolder extends RecyclerView.ViewHolder {
TextView tvSubItemTitle;
Switch checkBox;
SubItemViewHolder(View itemView) {
super(itemView);
tvSubItemTitle = itemView.findViewById(R.id.tv_sub_item_title);
checkBox = itemView.findViewById(R.id.switch1);
}
}
}
layout_sub_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="12dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/img_sub_item"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#color/colorPrimaryDark"
android:src="#drawable/ic_launcher_foreground"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/img_sub_item"
android:padding="12dp"
android:orientation="vertical">
<TextView
android:id="#+id/tv_sub_item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Sub item title"/>
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
layout_item.xml
<?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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="#f3f3f3"
app:cardElevation="8dp"
android:layout_margin="12dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="12dp"
android:orientation="vertical">
<TextView
android:id="#+id/tv_item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12sp"
android:textSize="18sp"
android:text="Item Title"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_sub_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Any help would be appreciated. Thanks!
Related
So, I have a three items in a recyclerview and I want to check if one of the field is unique or not in my case it's name. all the fields are shown correctly on the screen but whenever I call checkValidation it always returns false even when two names are not the same. I have a list and whenever I call from the activity it shows some different values as not how it is on the screen. If there is anything you didn't get kindly please comment.
dear community I really need help here..
Let me know what part you really didn't get.. :/
MainActivity.java
public MainActivity extends AppCompatActivity implements someinterface
..
..
#OnClick(R.id.activity_detailed_proceed)
void goToOrderPage() {
if (checkValidation()) {
startActivity(new Intent(MainActivity.this, Destination.class));
} else {
SameNameAlertDialogFragment sameNameAlertDialogFragment = new SameNameAlertDialogFragment();
sameNameAlertDialogFragment.show(getSupportFragmentManager(), "ERROR DIALOG");
}
}
..
..
boolean checkValidation() {
//
ArrayList<PersonFriends> personList = personAdapter.getPersonList();
ArrayList<String> namesList = new ArrayList<>();
for (int i = 0; i < personList.size(); i++) {
namesList.add(personList.get(i).getName());
System.out.println(personList.get(i).getName());
}
boolean corrent = true;
Set<String> set = new HashSet<String>(namesList);
if (set.size() < namesList.size()) {
//duplicates found
Log.d(TAG, "False was called here");
return false;
}
return true;
}
PersonAdapter personAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_selected_therapy);
ButterKnife.bind(this);
ArrayList<PersonFriends> personList = new ArrayList<>();
personAdapter = new PersonAdapter(this, this);
personRecyclerview.setAdapter(personAdapter);
personRecyclerview.setNestedScrollingEnabled(false);
personRecyclerview.setLayoutManager(new LinearLayoutManager(this));
}
some interface setup to get the name and duration
#Override
public void onPersonDetailClicked(int position, View view) {
if (view.getId() == R.id.person_name) {
adapterPosition = position;
EnterPersonDialogFragment enterPersonDialogFragment = new EnterPersonDialogFragment();
enterPersonDialogFragment.show(getSupportFragmentManager(), "PERSONS SELECTED");
}
if (view.getId() == R.id.delete_person) {
personAdapter.removeItem(position);
// personAdapter.setPersonList(personList);
// personAdapter.notifyItemRemoved(position);
}
if (view.getId() == R.id.person_duration) {
adapterPosition = position;
DurationDialogFragment durationDialogFragment = new DurationDialogFragment();
durationDialogFragment.show(getSupportFragmentManager(), "DURATION SELECTED");
}
}
#Override
public void enteredInName(String name) {
//change the list that is inside the adapter.
personAdapter.getPersonList().get(adapterPosition).setName(name);
personAdapter.notifyItemChanged(adapterPosition, PersonAdapter.PAYLOAD_NAME);
}
#Override
public void durationSelectedIs(String duration) {
personAdapter.getPersonList().get(adapterPosition).setduration(duration);
personAdapter.notifyItemChanged(adapterPosition, PersonAdapter.PAYLOAD_DURATION);
}
PersonAdapter.java
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> {
public static final String PAYLOAD_NAME = "PAYLOAD_NAME";
public static final String PAYLOAD_DURATION = "PAYLOAD_DURATION";
public static final String PAYLOAD_DATE = "PAYLOAD_DATE";
public static final String TAG = PersonAdapter.class.getSimpleName();
Context context;
ArrayList<PersonFriends> personList;
onPersonItemClicked onPersonItemClicked;
public PersonAdapter(Context context, onPersonItemClicked personItemClickListener) {
this.context = context;
onPersonItemClicked = personItemClickListener;
}
public void setPersonList(ArrayList<PersonFriends> personList) {
this.personList = personList;
notifyDataSetChanged();
}
public ArrayList<PersonFriends> getPersonList() {
return this.personList;
}
public void removeItem(int position) {
personList.remove(position);
notifyItemRemoved(position);
}
#NonNull
#Override
public PersonAdapter.PersonViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_persons_details, parent, false);
return new PersonViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PersonAdapter.PersonViewHolder holder, int position) {
PersonFriends Person = personList.get(position);
holder.personName.setText(Person.getName());
holder.personDate.setText(Person.getDate());
holder.personDuration.setText(Person.getduration());
if (position == 0) {
holder.deleteFab.hide();
}
}
#Override
public void onBindViewHolder(#NonNull PersonViewHolder holder, int position, #NonNull List<Object> payloads) {
if (!payloads.isEmpty()) {
final PersonFriends item = personList.get(position);
for (final Object payload : payloads) {
if (payload.equals(PAYLOAD_NAME)) {
// in this case only name will be updated
holder.personName.setText(item.getName());
} else if (payload.equals(PAYLOAD_DURATION)) {
// only age will be updated
holder.personDuration.setText(item.getduration());
} else if (payload.equals(PAYLOAD_DATE)) {
holder.personDate.setText(item.getDate());
}
}
} else {
// in this case regular onBindViewHolder will be called
super.onBindViewHolder(holder, position, payloads);
}
}
#Override
public int getItemCount() {
return personList.size();
}
public interface onPersonItemClicked {
void onPersonDetailClicked(int position, View view);
}
class PersonViewHolder extends RecyclerView.ViewHolder {
private final View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
onPersonItemClicked.onPersonDetailClicked(getAdapterPosition(), view);
}
};
#BindView(R.id.person_name)
TextView personName;
#BindView(R.id.person_date)
TextView personDate;
#BindView(R.id.person_duration)
TextView personDuration;
#BindView(R.id.delete_person)
FloatingActionButton deleteFab;
public PersonViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
personName.setOnClickListener(onClickListener);
personDate.setOnClickListener(onClickListener);
personDuration.setOnClickListener(onClickListener);
deleteFab.setOnClickListener(onClickListener);
}
}
}
item_persons_details.xml
<HorizontalScrollView 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"
android:layout_gravity="center|top"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="24dp"
android:background="#drawable/bg_rounded_30"
android:padding="8dp"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:text="NAME">
</TextView>
<TextView
android:id="#+id/person_duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:background="#drawable/bg_rounded_30"
android:drawableEnd="#drawable/ic_bottom_arrow"
android:drawablePadding="5dp"
android:padding="8dp"
android:text="DURATION">
</TextView>
<TextView
android:id="#+id/person_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:background="#drawable/bg_rounded_30"
android:drawableEnd="#drawable/ic_bottom_arrow"
android:drawablePadding="4dp"
android:padding="8dp"
android:text="MYDATE">
</TextView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/delete_person"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|center"
android:layout_margin="4dp"
android:backgroundTint="#color/colorBackground"
android:foregroundGravity="right"
android:outlineSpotShadowColor="#color/white"
android:src="#drawable/ic_bin"
android:tint="#color/colorBlack"
app:backgroundTint="#color/white"
app:fabCustomSize="30dp"
app:layout_constraintBottom_toBottomOf="#id/material_card_layout"
app:layout_constraintStart_toStartOf="#id/material_card_layout"
app:layout_constraintTop_toBottomOf="#id/material_card_layout"
app:maxImageSize="20dp" />
</LinearLayout>
</HorizontalScrollView>
I am using a card view with a recyclerView.The problem I'm having is that the cards are not displaying the images and the text that is supposed to be displayed, all I get is empty cards. any way I could fix this or am I doing something wrong?
avctivitymain xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:padding="8dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
cardsport xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="120dp"
android:layout_height="190dp"
android:id="#+id/car_lay"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:cardview="http://schemas.android.com/tools"
android:layout_margin="5dp"
app:cardCornerRadius="4dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/sport_image"
android:layout_width="match_parent"
android:layout_height="160dp"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/sport_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="14sp"
android:gravity="center"
android:text="frgrggr"
android:textColor="#2d2d2d"/>
</LinearLayout>
</android.support.v7.widget.CardView>
recyclerview adapter class
import java.util.List;
public class Recycler_view extends RecyclerView.Adapter<Recycler_view.myViewHolder>
{
private Context mContext;
private List<card> mData;
public Recycler_view(Context mContext, List<card> mData)
{
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View v;
LayoutInflater mflate = LayoutInflater.from(mContext);
v = mflate.inflate(R.layout.card_sport,parent,false);
return new myViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position)
{
holder.sport_txt.setText(mData.get(position).getType_sport());
holder.image_view.setImageResource(mData.get(position).getImages());
}
#Override
public int getItemCount()
{
return mData.size();
}
public static class myViewHolder extends RecyclerView.ViewHolder
{
TextView sport_txt;
ImageView image_view;
CardView cv;
public myViewHolder(View itemView)
{
super(itemView);
sport_txt = itemView.findViewById(R.id.sport_title);
image_view = itemView.findViewById(R.id.sport_image);
cv = itemView.findViewById(R.id.car_lay);
}
}
}
Main activity java class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
List<card> card_sport;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
card_sport = new ArrayList<>();
// ADDING DATA TO THE CARD ARRAYLIST
card_sport.add(new card("soccer",R.drawable.soccer));
card_sport.add(new card("Cage Fighting",R.drawable.cagef));
card_sport.add(new card("Cricket",R.drawable.cricket));
card_sport.add(new card("WaterPolo",R.drawable.polo));
card_sport.add(new card("Running",R.drawable.runman));
card_sport.add(new card("Swimming",R.drawable.swim));
card_sport.add(new card("Rugby",R.drawable.rugby));
RecyclerView rv = findViewById(R.id.recyclerview);
Recycler_view re_adapter = new Recycler_view(this, card_sport);
rv.setLayoutManager(new GridLayoutManager(this,2));
rv.setAdapter(re_adapter);
}
}
card java class for getters and setters
package com.example.dalian.cool_jungle;
public class card
{
private String type_sport;
private int images;
public card()
{
}
public card(String type_sport,int images)
{
type_sport= type_sport;
images = images;
}
public String getType_sport()
{
return type_sport;
}
public int getImages()
{
return images;
}
public void setType_sport()
{
type_sport =type_sport;
}
public void setImages()
{
images = images;
}
}
log
line 17
line 47
after a taken "this" out my card class it just shows blank cards
Your all above code are fine. There will no problem if you made your card object correctly. That may be like:
public class card {
private String type_sport;
private int image;
public card(String type_sport, int image) {
this.type_sport = type_sport;
this.image = image;
}
public String getType_sport() {
return type_sport;
}
public void setType_sport(String type_sport) {
this.type_sport = type_sport;
}
public int getImages() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
You don't need to pass the context in, you can get it from the parent viewgroup. You also don't need to make the view holder a static class, that might help.
I've explored many ways to achieve this. But I'm much confused now. I tried many Githubs libraries but got confused. Also tried this but I don't think it allows a textview to be shown in expanded view: http://bignerdranch.github.io/expandable-recycler-view/
WHAT I WANT: A simple Recyclerview fetching some text from server for different items. On each item click, a layout or view should be expanded and TextView should become visible with respective fetched text from the server.
I have a simple RecyclerView with code following:
DataAdapter.java
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<List> android_versions;
private Context context;
int i =0;
public DataAdapter(Context context,ArrayList<List> android_versions) {
this.context = context;
this.android_versions = android_versions;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.tv_android.setText(android_versions.get(i).getAndroid_version_name());
}
#Override
public int getItemCount() {
return android_versions.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView tv_android;
public ViewHolder(View view) {
super(view);
tv_android = (TextView)view.findViewById(R.id.tv_android);
}
}
List.java (Some functions aren't being used as of now)
public class List {
private String android_version_name;
private String descr;
private int android_image_url;
private String android_image_url1;
public String getAndroid_version_name() {
return android_version_name;
}
public String getDescr(){ return descr;}
public void setDescr(String descr) {
this.descr = descr;
}
public void setAndroid_version_name(String android_version_name) {
this.android_version_name = android_version_name;
}
public int getAndroid_image_url() {
return android_image_url;
}
public String getAndroid_image_url1() {
return android_image_url1;
}
public void setAndroid_image_url(int android_image_url) {
this.android_image_url = android_image_url;
}
public void setAndroid_image_url1(String android_image_url1) {
this.android_image_url1 = android_image_url1;
}
}
row_layout.xml
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
card_view:cardCornerRadius="5dp"
android:background="#drawable/custom_bg"
android:clickable="true"
android:translationZ="3dp"
android:elevation="1dp"
android:focusable="true">
<RelativeLayout
android:layout_marginLeft="0dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/custom_bg">
<TextView
android:layout_marginTop="10dp"
android:textSize="20sp"
android:layout_marginRight="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_android"
android:textStyle="normal"
android:layout_centerVertical="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Work.java (It's a fragment)
String[] sublist={
"English",
"Hindi"
};
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
rcl = (RecyclerView) getActivity().findViewById(R.id.homeworklist);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
rcl.setLayoutManager(layoutManager);
dataAdapter = new DataAdapter(getActivity(), new ArrayList<>(prepareData()));
rcl.setAdapter(dataAdapter);
}
public ArrayList prepareData(){
ArrayList android_version = new ArrayList<>();
for(int i=0;i<sublist.length;i++){
List androidVersion = new List();
androidVersion.setAndroid_version_name(sublist[i]);
android_version.add(androidVersion);
break;
}
return android_version;
}
I have tried many ways to add recyclerview inside a fragment. I'm new for android. My android have 5 fragments one of these fragment I need to add a recyclerview. here is my code
notification_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/notification_item_root"
android:layout_width="match_parent"
android:layout_height="56dp"
android:gravity="center_vertical|left"
android:orientation="horizontal"
android:paddingLeft="16dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/notification_item_img"
android:layout_width="36dp"
android:layout_height="36dp"
android:src="#android:drawable/ic_input_get" />
<TextView
android:id="#+id/notification_item_text"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:paddingLeft="8dp"
android:text="Test Testre" />
</LinearLayout>
notification_Fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.app.AlertController.RecycleListView
android:id="#+id/notification_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
NotificationItem.java
public class NotificationItem {
private String title;
private int imageResId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImageResId() {
return imageResId;
}
public void setImageResId(int imageResId) {
this.imageResId = imageResId;
}
}
NotificationData.java
public class NotificationData {
private static final String[] textItem = {"pathum", "sai", "charu"};
private static final int[] imgItem = {android.R.drawable.ic_popup_reminder, android.R.drawable.ic_menu_add, android.R.drawable.ic_menu_delete};
public static List<NotificationItem> getListData() {
List<NotificationItem> data = new ArrayList<>();
for (int x = 0; x < 4; x++) {
for (int i = 0; i < textItem.length && i < imgItem.length; i++) {
NotificationItem item = new NotificationItem();
item.setImageResId(imgItem[i]);
item.setTitle(textItem[i]);
data.add(item);
}
}
return data;
}
}
NotificationAdapter.java
public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.NotificationHolder> {
private List<NotificationItem> listData;
private LayoutInflater inflater;
public NotificationAdapter(List<NotificationItem> listData, Context c) {
this.inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public NotificationHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.notification_item,parent,false);
return new NotificationHolder(view);
}
#Override
public void onBindViewHolder(NotificationHolder holder, int position) {
NotificationItem item = listData.get(position);
holder.title.setText(item.getTitle());
holder.icon.setImageResource(item.getImageResId());
}
#Override
public int getItemCount() {
return listData.size();
}
class NotificationHolder extends RecyclerView.ViewHolder {
private TextView title;
private CircleImageView icon;
private View container;
public NotificationHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.notification_item_text);
icon = (CircleImageView) itemView.findViewById(R.id.notification_item_img);
container = itemView.findViewById(R.id.notification_item_root);
}
}
}
NotificationFragment.java
public class NotificationFragment extends Fragment {
RecyclerView recyclerView;
NotificationAdapter notificationAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.notification_fragment, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.notification_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
notificationAdapter = new NotificationAdapter(NotificationData.getListData(),this);
recyclerView.setAdapter(notificationAdapter);
return rootView;
}
}
I was unable to make it right in NotificationFragment.java and NotificationAdapter.java please help me guys.
You are using wrong class for RecyclerView, instead of AlertController.RecyclerListView use this:
<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Here are some more informations:
RecyclerView
1) first add dependency to your app level gradle file then sync your project
compile 'com.android.support:recyclerview-v7:23.4.0'
2) go to your Layout file (eg: activity_main.xml) add recyclerview tag inside your base layout
<RelativeLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.examples.rehan.excluzo.Fragments.OneFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
3) create a class model.java and paste your code.
public class model{
private String name, gender;
public model() {
}
public model(String name, String gender) {
this.name= name;
this.gender= gender;
}
public String getGender() {
return gender;
}
public void setGender(String gneder) {
this.gender= gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
}
4)create xml file in your layout folder item_layout.xml and paste this code
<?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"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp" >
<TextView
android:id="#+id/name"
android:textColor="#color/title"
android:textSize="16dp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/gender"
android:layout_below="#id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
5)your need to create adapter to add child views to your listview. so create a file testAdapter.java file and paste this code.
here in list view i will be having only 2 items(eg : Name and gender)
public class testAdapter extends RecyclerView.Adapter<testAdapter.MyViewHolder> {
private List<model> productList;
Context context;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
model product = productList.get(position);
holder.name.setText(product.getName());
holder.gender.setText(product.getGender());
}
#Override
public int getItemCount() {
return productList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name,gender;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
gender = (TextView) view.findViewById(R.id.gender);
}
}
public testAdapter(List<model> productList, Context context) {
this.productList = productList;
this.context = context;
}
}
6) now goto your MainActivity.java and paste this code
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<modle> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private testAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new testAdapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
preparedata();
}
private void preparedata() {
model movie = new model("XXX", "Male");
movieList.add(movie);
//add the items according to your wish
//name,gender
//here i have added all items with same name and gender. you can change it
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
}
}
Hope this helps :)
I am trying to populate CardView's inside a RecyclerView. Though I am able to log all the adapter values(to make sure they are non-empty) I can't populate any in the UI. Here is the Activity Code:
FoodActivity.class
public class FoodActivity extends AppCompatActivity
{
private RecyclerView foodView;
private List<Result> adapter_data;
private CustomPlacesAdapter adapter;
private LinearLayoutManager llm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
foodView = (RecyclerView)findViewById(R.id.foodRView);
adapter = new CustomPlacesAdapter(adapter_data);
adapter_data = new ArrayList<>();
llm = new LinearLayoutManager(this);
foodView.setLayoutManager(llm);
foodView.setAdapter(adapter);
doGetRequest("restaurants in los angeles airport");
}
private void doGetRequest(final String message)
{
ApiInterfacePlaces apiService =
ApiClientPlaces.getClient().create(ApiInterfacePlaces.class);
Call<PlacesPojo> call = apiService.getValues(message, Util.getKeyForPlaces());
call.enqueue(new Callback<PlacesPojo>()
{
#Override
public void onResponse(Call<PlacesPojo>call, Response<PlacesPojo> response)
{
try
{
Log.e("TAG",""+response.body().toString());
List<Result> response_res = response.body().getResults();
adapter_data = response_res;
adapter.notifyDataSetChanged();
}
catch (Exception e)
{
Toast.makeText(FoodActivity.this, "Check data connection", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<PlacesPojo> call, Throwable t) {
// Log error here since request failed
Log.e("FAILURE", t.toString());
}
});
}
}
Here is the code to the RecyclerView's adapter:
CustomPlacesAdapter.class
public class CustomPlacesAdapter extends RecyclerView.Adapter<CustomPlacesAdapter.HotelsViewHolder>
{
private DataHolder d2 = new DataHolder();
public class HotelsViewHolder extends RecyclerView.ViewHolder
{
private TextView hotelName;
private Typeface face;
private ImageView hotel_logo;
private Context mcontext;
HotelsViewHolder(View itemView)
{
super(itemView);
mcontext = itemView.getContext();
hotelName = (TextView)itemView.findViewById(R.id.hotelName);
face = Typeface.createFromAsset(itemView.getContext().getAssets(), "Fonts/Roboto-Regular.ttf");
hotelName.setTypeface(face);
hotel_logo = (ImageView)itemView.findViewById(R.id.logoOfHotel);
}
}
private static class DataHolder
{
List<Result> feeds;
}
public CustomPlacesAdapter(List<Result> feeds)
{
this.d2.feeds = feeds;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public HotelsViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.food_item, viewGroup, false);
HotelsViewHolder pvh = new HotelsViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(HotelsViewHolder feedViewHolder, int i)
{
feedViewHolder.hotelName.setText(d2.feeds.get(i).getName());
Picasso.with(feedViewHolder.mcontext).load(d2.feeds.get(i).getIcon()).into(feedViewHolder.hotel_logo);
}
#Override
public int getItemCount()
{
if(d2.feeds!=null)
{
return d2.feeds.size();
}
else
{
return 0;
}
}
}
This is the CardView that I use:
food_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_centerHorizontal="true"
app:cardCornerRadius="5dp"
android:layout_height="100dp"
card_view:cardUseCompatPadding="false"
android:id="#+id/cv">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/logoOfHotel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/hotelName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Cross checked many things, still unable to fix the issue, what is possibly causing this? Any help would be much appreciated.