Populating a RecyclerView with CardView tied to an ArrayList - java

I am trying to create a swipeable CardView list inside a RecyclerView. However, none of the string values appear in the CardViews when I run the app.
This is my MainActivity class:
public class MainActivity extends Activity {
private CardViewAdapter mAdapter;
Button periodicbutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
periodicbutton = (Button) findViewById(R.id.periodbutton);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] values = new String[] {"Quantitative Chemistry", "Atomic Structure", "Periodicity",
"Bonding", "Energetics","Kinetics","Equilibrium","Acids & Bases","Oxidation & Reduction","Organic Chemistry"};
final ArrayList<String> mItems = new ArrayList<>();
for (int i = 0; i < values.length; i++) {
mItems.add(values[i]);
}
OnItemTouchListener itemTouchListener = new OnItemTouchListener() {
#Override
public void onCardViewTap(View view, int position) {
Toast.makeText(MainActivity.this, "Swipe me", Toast.LENGTH_SHORT).show();
}
};
mAdapter = new CardViewAdapter(mItems, itemTouchListener);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
recyclerView.setHasFixedSize(false);
SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(recyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
#Override
public boolean canSwipe(int position) {
return true;
}
#Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
// Toast.makeText(MainActivity.this, mItems.get(position) + " swiped left", Toast.LENGTH_SHORT).show();
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
// Toast.makeText(MainActivity.this, mItems.get(position) + " swiped right", Toast.LENGTH_SHORT).show();
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
});
recyclerView.addOnItemTouchListener(swipeTouchListener);
}
public interface OnItemTouchListener {
/**
* Callback invoked when the user Taps one of the RecyclerView items
*
* #param view the CardView touched
* #param position the index of the item touched in the RecyclerView
*/
void onCardViewTap(View view, int position);
}
public class CardViewAdapter extends RecyclerView.Adapter<CardViewAdapter.ViewHolder> {
private List<String> cards;
private OnItemTouchListener onItemTouchListener;
public CardViewAdapter(List<String> cards, OnItemTouchListener onItemTouchListener) {
this.cards = cards;
this.onItemTouchListener = onItemTouchListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_layout, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
}
#Override
public int getItemCount() {
return cards == null ? 0 : cards.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemTouchListener.onCardViewTap(v, getPosition());
}
});
}
}
}
}
This is my activity_main.xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
android:orientation="vertical"
android:scrollbars="vertical">
<android.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="fill_parent"
android:layout_height="72dp"
android:background="#color/primary">
</android.widget.Toolbar>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical" >
</android.support.v7.widget.RecyclerView>
</LinearLayout>
This is the card_view.xml file I'm trying to tie the string values to:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<android.support.v7.widget.CardView
android:id="#+id/quantutative"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="vertical"
card_view:cardCornerRadius="4dp">
<TextView
android:layout_width="fill_parent"
android:layout_height="54dp"
android:gravity="center_vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:textColor="#color/card_text"
android:textSize="36sp"
/>
</android.support.v7.widget.CardView>
</LinearLayout>

Related

How to change TextView in Activity by delete button in RecyclerView?

When I add an item by button Scan Now, the public double sumCost value incrementes by the cost value in the AddItem method and then TextView(android:id="#+id/SumText") assigns this value. And How to decrease sumCost by the number that is in cost and set new text in TextView when pressing the Delete button? Thanks for any help
enter image description here
My full code:
MainActivity:
package com.example.testfirst;
...
public class MainActivity extends AppCompatActivity {
TextView sumText;
Button buttonAdd;
List<Contact> contacts = new LinkedList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
buttonAdd = (Button) findViewById(R.id.scanBtn);
sumText = (TextView) findViewById(R.id.SumText);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddItem("Tom", 2.45);
sumText.setText(Double.toString(sumCost));
}
});
}
public void AddItem(String name, double cost){
sumCost += cost;
RecyclerView rvContacts = (RecyclerView) findViewById(R.id.recyclerView);
ContactsAdapter adapter = new ContactsAdapter(contacts);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
contacts.add(new Contact(name,Double.toString(cost)));
}
public double sumCost = 0;
}
Contact(Model class):
...
public class Contact {
private String mName;
private String mCost;
public Contact(String name, String cost) {
mName = name;
mCost = cost;
}
public String getName() {
return mName;
}
public String getCost() {
return mCost;
}
}
ContactsAdapter:
...
public class ContactsAdapter extends RecyclerView.Adapter<ViewHolder>{
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.item_contact, parent, false);
return new ViewHolder(contactView).linkAdapter(this);
}
///////////////
#NonNull
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Contact contact = mContacts.get(position);
TextView textViewId = holder.nameId;
textViewId.setText(contact.getName());
TextView textViewCost = holder.nameCost;
textViewCost.setText(contact.getCost());
}
#Override
public int getItemCount() {
return mContacts.size();
}
List<Contact> mContacts;
public ContactsAdapter(List<Contact> contacts) {
mContacts = contacts;
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private ContactsAdapter adapter;
public TextView nameId;
public TextView nameCost;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameId = (TextView) itemView.findViewById(R.id.text);
nameCost = (TextView) itemView.findViewById(R.id.textCost);
itemView.findViewById(R.id.delete).setOnClickListener(view -> {
adapter.mContacts.remove(getAdapterPosition());
adapter.notifyItemRemoved(getAdapterPosition());
});
}
public ViewHolder linkAdapter(ContactsAdapter adapter){
this.adapter = adapter;
return this;
}
}
item_contact.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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_margin="10dp"
app:cardCornerRadius="10dp"
app:cardElevation="5dp"
app:contentPadding="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/app_name"
android:textSize="20sp" />
<TextView
android:id="#+id/textCost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text"
android:text="#string/app_name"
android:textSize="20sp" />
<Button
android:id="#+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="3dp"
android:layout_marginEnd="3dp"
android:text="Delete" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
activity_users.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/SumText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="0.00"
android:textSize="30sp"/>
<Button
android:id="#+id/scanBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scan now"
android:textSize="30sp"
android:layout_gravity="center_horizontal"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
One easy way to do that would be do add a "Decrementer" interface in the adapter that it can call to decrement the total cost, like this:
// Define the interface
public interface Decrementer {
void onDelete(double cost);
}
// Define an instance of the interface to hold
private final Decrementer mDecrementer;
// Pass in a decrementer at construction
public ContactsAdapter(List<Contact> contacts, Decrementer decr) {
mContacts = contacts;
mDecrementer = decr;
}
#NonNull
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// get views and such ...
// Call the decrementer method when the button is clicked
// Could set this in onBindViewHolder, or pass the decrementer
// into the ViewHolder itself and use it there.
deleteButton.setOnClickListener(view -> {
int pos = holder.getAdapterPosition();
Contact c = mContacts.get(pos);
// add getCostAmount to return a double, or better yet, just
// store it as a Double instead of a string in Contact
mDecrementer.onDelete(c.getCostAmount());
mContacts.remove(pos);
notifyItemRemoved(pos);
});
}
and you would define the Decrementer when you create the adapter so it can access the Activity class members, like this:
ContactsAdapter adapter = new ContactsAdapter(contacts, new ContactsAdapter.Decrementer() {
#Override
public void onDelete(double cost) {
sumCost -= cost;
// change activity TextViews and such here too
sumText.setText(Double.toString(sumCost));
}
});
Side note: you don't need to create a whole new adapter every time you add an item, just add it to the contacts array and call an appropriate notifyDataSetChanged method on the existing adapter.
private ContactsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
//...
RecyclerView rvContacts = (RecyclerView) findViewById(R.id.recyclerView);
ContactsAdapter adapter = new ContactsAdapter(contacts);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
}
public void AddItem(String name, double cost){
sumCost += cost;
contacts.add(new Contact(name,Double.toString(cost)));
adapter.notifyDataSetChanged(); // or a less expensive notify call
}

RecyclerView Items Duplicating when navigating through different Fragments, arraylist.clear() doesn´t work

This is my first post here. I´m having trouble with a RecyclerView which I´m using into a fragment. I have two different fragments for a BottomNavigationMenu and the items duplicate everytime I get back to the fragment where the RecyclerView is in. I have tried using arraylist.clear(); as it is been suggested many times here but it doesn´t work. I have used the exact same code before using TabLayout with fragments instead of BottomNavigationMenu and it worked fine! the items didn´t duplicate at all... I´m making a music library for an audio streaming app and I´m using realtime firebase to print the information for the RecyclerView onto the screen, if I use: if (audioFileArrayList == null) {
loadData();
} it fixes the issue beacuse this way it doesn´t print the information twice but I don´t think this is a proper solution to this problem. It seems as if everytime I go back to the RecyclerView fragment the view doesn´t refresh but instead it prints everything again and again at the bottom...
This is the MainActivity:
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
getSupportActionBar().hide(); //escondemos la action bar
bottomNavigationView = binding.bottomNavigationID;
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_id, new BibliotecaFragment()).commit();
bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragmentSeleccionado = null;
switch (item.getItemId()) {
case R.id.biblioteca_ID:
fragmentSeleccionado = new BibliotecaFragment();
break;
case R.id.playlists_ID:
fragmentSeleccionado = new PlayListsFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_id, fragmentSeleccionado).commit();
return true;
}
});
}
}
This is the fragment for the library, as I said before if I use
if (audioFileArrayList == null) {
loadData();
}
it stops it from printing it twice.
public class BibliotecaFragment extends Fragment {
FragmentBibliotecaBinding binding;
RecyclerView recyclerView;
AudioFileAdapter audioFileAdapter;
static ArrayList<AudioFile> audioFileArrayList;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentBibliotecaBinding.inflate(getLayoutInflater());
recyclerView = binding.BibliotecaFragmentRecyclerViewID;
recyclerView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(manager);
audioFileAdapter = new AudioFileAdapter(getContext());
recyclerView.setAdapter(audioFileAdapter);
loadData();
return binding.getRoot();
}
public void loadData() {
DatabaseReference dbr = FirebaseDatabase.getInstance().getReference();
dbr.child("biblioteca").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
audioFileArrayList = new ArrayList<>();
for (DataSnapshot data : snapshot.getChildren()) {
AudioFile audioFile = data.getValue(AudioFile.class);
audioFileArrayList.add(audioFile);
}
audioFileAdapter.setItems(audioFileArrayList);
audioFileAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
This is my adapter:
public class AudioFileAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
static ArrayList<AudioFile> audioFileList = new ArrayList<>();
public AudioFileAdapter(Context ctx) {
this.context = ctx;
}
public void setItems(ArrayList<AudioFile> audioFile) {
audioFileList.addAll(audioFile);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.audio_item, parent, false);
return new AudioFileViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, #SuppressLint("RecyclerView") int position) {
AudioFileViewHolder audioFileViewHolder = (AudioFileViewHolder) holder;
AudioFile audioFile = audioFileList.get(position);
audioFileViewHolder.txtArtist.setText(audioFile.getArtist());
audioFileViewHolder.txtTitle.setText(audioFile.getTitle());
Glide.with(context).load(audioFile.getImgURL()).into(audioFileViewHolder.imageViewPicture);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putInt("posicion", position);
Intent intent = new Intent(context, Reproductor.class);
intent.putExtras(bundle);
context.startActivity(intent);
}
});
((AudioFileViewHolder) holder).imageViewMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popupMenu = new PopupMenu(context, view);
popupMenu.getMenuInflater().inflate(R.menu.audio_item_popup_menu, popupMenu.getMenu());
popupMenu.show();
popupMenu.setOnMenuItemClickListener((menuItem) -> {
switch (menuItem.getItemId()) {
case R.id.agregar_a_lista_ID: {
break;
}
case R.id.eliminar_de_biblioteca_ID: {
eliminar(position);
break;
}
}
return true;
});
}
});
}
public void eliminar(int position) {
String id = audioFileList.get(position).getId();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query delete = databaseReference.child("biblioteca").orderByChild("id").equalTo(id);
delete.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
audioFileList.clear(); // importante limpiar la lista cada vez que se elimina un item para que no se dupliquen en la parte de abajo...
for (DataSnapshot data : dataSnapshot.getChildren()) {
data.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return audioFileList.size();
}
public interface ItemClickListener { //interfaz listener para RyclerView
void onItemClick(AudioFile audioFile);
}
}
My ViewHolder:
public class AudioFileViewHolder extends RecyclerView.ViewHolder {
public TextView txtArtist, txtTitle;
public ImageView imageViewPicture, imageViewMenu;
public AudioFileViewHolder(#NonNull View itemView) {
super(itemView);
txtArtist = itemView.findViewById(R.id.artistID);
txtTitle = itemView.findViewById(R.id.titleID);
imageViewPicture = itemView.findViewById(R.id.item_imageID);
imageViewMenu = itemView.findViewById(R.id.item_menu_ID);
}
}
The XML code for MainActivity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/frame_layout_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation_ID" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation_ID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
app:menu="#menu/bottom_navigation_menu" />
</RelativeLayout>
The XML code for RecyclerView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BibliotecaFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/BibliotecaFragmentRecyclerViewID"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3C3A3A"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
And the XML code for each item into the RecyclerView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/audio_itemID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#color/black"
android:orientation="horizontal">
<ImageView
android:id="#+id/item_imageID"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#drawable/ic_launcher_foreground"
android:padding="5dp" />
<TextView
android:id="#+id/artistID"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center"
android:text="Artist"
android:textColor="#color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center"
android:text="-"
android:textColor="#color/white" />
<TextView
android:id="#+id/titleID"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center"
android:text="Title"
android:textColor="#color/white" />
<ImageView
android:id="#+id/item_menu_ID"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="150dp"
android:background="#drawable/ic_baseline_more_vert"
android:padding="5dp"
android:layout_gravity="center_vertical"/>
</LinearLayout>
Sorry for my english, I know it is not perfect, I hope you guys can help me with this.
Rubén.
I'm having the same problem and currently have no answer. You can try my method but only works if your recycler items are definite.
Goto your viewholder class=>
#Override
public int getItemCount() {
return num;
}
Where num is the number of your items in recyclerview.

How to show CardViews (with different content types) in RecyclerView

I'm trying to show an additional CardView that contains a different layout but have got lost with my code. I'm also unsure of how to to show the array of strings within a GridView for the CardView itself. Does anyone know where I may have gone wrong & what can be done so that the following can be achieved?:
Place the CardView containing the GridView wherever I want within the RecyclerView.
Show the array of strings in a GridView within a CardView
What I want to add to the RecyclerView (above the Item A CardView)
RecyclerView current contents
Fragment class
public class MyFragment extends android.support.v4.app.Fragment {
private MonRecyclerAdapterWithGrid adapterG;
static final String[] frenchVowels = new String[]{
"a", "e", "i", "o", "u", "y"
};
public MyFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_rv, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
View v = getView();
assert v != null;
recyclerView = v.findViewById(R.id.my_recyclerview);
linearLayoutManager = new LinearLayoutManager(getActivity());
MyRecyclerAdapter adapter = new MyRecyclerAdapter(getContext(), getHeader(), getListItemsG(), getListItemsT());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
super.onActivityCreated(savedInstanceState);
}
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
public RecyclerViewHeader getHeader()
{
return new RecyclerViewHeader();
}
public List<RecyclerViewItemGV> getListItemsG() {
List<RecyclerViewItemGV> rvItemsG = new ArrayList<>();
RecyclerViewItemGV itemG = new RecyclerViewItemGV();
itemG.setTitleGV("Item A");
itemG.setVowelsGV(adapterG);
for (String fVowels : frenchVowels) {
// ?????? Still not working :-(
adapterG.addAdapterItem(new MyFragment.AdapterItem(frenchVowels));
}
rvItemsG.add(itemG);
return rvItemsG;
}
public List<RecyclerViewItemTV> getListItemsT()
{
List<RecyclerViewItemTV> rvItemsT = new ArrayList<>();
RecyclerViewItemTV itemA = new RecyclerViewItemTV();
itemA.setTitleTV("Item A");
itemA.setDescriptionTV("Feature A1");
rvItemsT.add(itemA);
RecyclerViewItemTV itemB = new RecyclerViewItemTV();
itemB.setTitleTV("Item B");
itemB.setDescriptionTV("Feature B1\nFeature B2");
rvItemsT.add(itemB);
RecyclerViewItemTV itemC = new RecyclerViewItemTV();
itemC.setTitleTV("Item C");
itemC.setDescriptionTV("Feature C1\nFeature C2\nFeature C3");
rvItemsT.add(itemC);
return rvItemsT;
}
}
RecyclerView adapter class
public class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEMG = 1;
private static final int TYPE_ITEMT = 2;
private Context mContext;
RecyclerViewHeader header;
List<RecyclerViewItemGV> listItemsG;
List<RecyclerViewItemTV> listItemsT;
ValueAnimator mAnimator;
public MyRecyclerAdapter(Context context, RecyclerViewHeader header, List<RecyclerViewItemGV> listItemsG, List<RecyclerViewItemTV> listItemsT)
{
this.mContext = context;
this.header = header;
this.listItemsG = listItemsG;
this.listItemsT = listItemsT;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_HEADER)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_header_expandcollapsebuttons, parent, false);
return new MyRecyclerAdapter.VHHeader(v);
}
else if(viewType == TYPE_ITEMG)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_gv, parent, false);
return new MyRecyclerAdapter.VHItemG(v);
}
else if(viewType == TYPE_ITEMT)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_tv, parent, false);
return new MyRecyclerAdapter.VHItemT(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
private RecyclerViewItemGV getItemG(int position)
{
return listItemsG.get(position);
}
private RecyclerViewItemTV getItemT(int position)
{
return listItemsT.get(position);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Typeface iconFont = FontManager.getTypeface(mContext, FontManager.FONTAWESOME);
if (holder instanceof MyRecyclerAdapter.VHHeader)
{
final MyRecyclerAdapter.VHHeader vhHeader = (MyRecyclerAdapter.VHHeader)holder;
}
else if (holder instanceof MyRecyclerAdapter.VHItemG){
RecyclerViewItemGV currentItemG = getItemG(position-1);
final MonRecyclerAdapterWithGrid.VHItemG vhItemG = (MyRecyclerAdapter.VHItemG)holder;
vhItemG.txtAG.setText(currentItemG.getTitleGV());
vhItemG.mGridViewG.setVisibility(View.GONE);
vhItemG.txtExpandCollapseG.setText(R.string.fa_icon_chevron_down);
vhItemG.txtExpandCollapseG.setTypeface(iconFont);
//Add onPreDrawListener
vhItemG.mGridViewG.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
vhItemG.mGridViewG.getViewTreeObserver().removeOnPreDrawListener(this);
vhItemG.mGridViewG.setVisibility(View.GONE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
vhItemG.mGridViewG.measure(widthSpec, heightSpec);
vhItemG.mGridViewHeight = vhItemG.mGridViewG.getMeasuredHeight();
return true;
}
});
vhItemG.mCardViewG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(vhItemG.mGridViewG.getVisibility() == View.GONE){
vhItemG.expandG();
} else {
vhItemG.collapseG();
}
}
});
}
else if (holder instanceof MyRecyclerAdapter.VHItemT)
{
RecyclerViewItemTV currentItem = getItemT(position-2);
final MyRecyclerAdapter.VHItemT vhItemT = (MyRecyclerAdapter.VHItemT)holder;
vhItemT.txtA.setText(currentItem.getTitleTV());
vhItemT.txtB.setText(currentItem.getDescriptionTV());
vhItemT.txtB.setVisibility(View.GONE);
vhItemT.txtExpandCollapse.setText(R.string.fa_icon_chevron_down);
vhItemT.txtExpandCollapse.setTypeface(iconFont);
//Add onPreDrawListener
vhItemT.txtB.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
vhItemT.txtB.getViewTreeObserver().removeOnPreDrawListener(this);
vhItemT.txtB.setVisibility(View.GONE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
vhItemT.txtB.measure(widthSpec, heightSpec);
vhItemT.textBHeight = vhItemT.txtB.getMeasuredHeight();
return true;
}
});
vhItemT.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(vhItemT.txtB.getVisibility() == View.GONE){
vhItemT.expandT();
} else {
vhItemT.collapseT();
}
}
});
}
}
// need to override this method
#Override
public int getItemViewType(int position) {
if(isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEMG;
return TYPE_ITEMT;
}
private boolean isPositionHeader(int position)
{
return position == 0;
}
#Override
public int getItemCount() {
return listItemsG.size()+1;
return listItemsT.size()+1;
}
class VHHeader extends RecyclerView.ViewHolder{
Button btnCollapseAll, btnExpandAll;
public VHHeader(View headerView) {
super(headerView);
this.btnCollapseAll = headerView.findViewById(R.id.btn_collapseall);
this.btnExpandAll = headerView.findViewById(R.id.btn_expandall);
}
}
public class VHItemG extends RecyclerView.ViewHolder{
CardView mCardViewG;
LinearLayout mLinearLayoutG;
RelativeLayout mRelativeLayoutG;
RecyclerView mRecyclerViewG;
GridView mGridViewG;
TextView txtExpandCollapseG, txtAG;
public int mGridViewHeight;
public VHItemG(View itemView) {
super(itemView);
this.mCardViewG = itemView.findViewById(R.id.cv_gv);
this.mLinearLayoutG = itemView.findViewById(R.id.linearlayout_gv_titlerow);
this.mRelativeLayoutG = itemView.findViewById(R.id.relativelayout_gv);
this.mRecyclerViewG = itemView.findViewById(R.id.my_recyclerview);
this.txtAG = itemView.findViewById(R.id.tv_gv_A);
this.txtExpandCollapseG = itemView.findViewById(R.id.tv_gv_expandcollapse);
this.mGridViewG = itemView.findViewById(R.id.gv_a);
}
private void expandG() {
// change visibility to 'VISIBLE'
mGridViewG.setVisibility(View.VISIBLE);
// change direction of chevron to 'up'
txtExpandCollapseG.setText(R.string.fa_icon_chevron_up);
// apply animation to the height of 'txtB'
mAnimator = slideAnimator(0, mGridViewHeight);
// start the animation
mAnimator.start();
}
private void collapseG() {
// change direction of chevron to 'down'
txtExpandCollapseG.setText(R.string.fa_icon_chevron_down);
int finalHeight = mGridViewG.getHeight();
ValueAnimator mAnimator = slideAnimator(finalHeight, 0);
mAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
// Height will be 0, but set visibility to 'GONE'
mGridViewG.setVisibility(View.GONE);
}
#Override
public void onAnimationStart(Animator animator) {
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
mAnimator.start();
}
public ValueAnimator slideAnimator(int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
// update height
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = mGridViewG.getLayoutParams();
layoutParams.height = value;
mGridViewG.setLayoutParams(layoutParams);
}
});
return animator;
}
}
public class VHItemT extends RecyclerView.ViewHolder{
CardView cardView;
LinearLayout mLinearLayout;
RecyclerView mRecyclerView;
RelativeLayout mRelativeLayout;
TextView txtExpandCollapse, txtA, txtB;
public int textBHeight;
public VHItemT(View itemView) {
super(itemView);
this.cardView = itemView.findViewById(R.id.linearlayout_tv_main);
this.mLinearLayout = itemView.findViewById(R.id.linearlayout_tv_titlerow);
this.mRelativeLayout = itemView.findViewById(R.id.relativelayout_tv);
this.mRecyclerView = itemView.findViewById(R.id.my_recyclerview);
this.txtExpandCollapse = itemView.findViewById(R.id.tv_tv_expandcollapse);
this.txtA = itemView.findViewById(R.id.tv_tv_A);
this.txtB = itemView.findViewById(R.id.tv_tv_B);
}
private void expandT() {
// change visibility to 'VISIBLE'
txtB.setVisibility(View.VISIBLE);
// change direction of chevron to 'up'
txtExpandCollapse.setText(R.string.fa_icon_chevron_up);
// apply animation to the height of 'txtB'
mAnimator = slideAnimator(0, textBHeight);
// start the animation
mAnimator.start();
}
private void collapseT() {
// change direction of chevron to 'down'
txtExpandCollapse.setText(R.string.fa_icon_chevron_down);
int finalHeight = txtB.getHeight();
ValueAnimator mAnimator = slideAnimator(finalHeight, 0);
mAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
// Height will be 0, but set visibility to 'GONE'
txtB.setVisibility(View.GONE);
}
#Override
public void onAnimationStart(Animator animator) {
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
mAnimator.start();
}
public ValueAnimator slideAnimator(int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
// update height
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = txtB.getLayoutParams();
layoutParams.height = value;
txtB.setLayoutParams(layoutParams);
}
});
return animator;
}
}
}
GridView adapter (currently excluded from project)
private class MyGVAdapter extends ArrayAdapter<AdapterItem> {
private List<AdapterItem> items = new ArrayList<>();
MyGVAdapter(Context context, int textviewid) {
super(context, textviewid);
}
void addAdapterItem(MyGVFragment.AdapterItem item) {
items.add(item);
}
#Override
public int getCount() {
return items.size();
}
#Override
public MyGVFragment.AdapterItem getItem(int position) {
return ((null != items) ? items.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull final ViewGroup parent) {
View rowView;
if (convertView == null) {
rowView = getActivity().getLayoutInflater().inflate(R.layout.gridview_item, parent, false);
} else {
rowView = convertView;
}
TextView tv = rowView.findViewById(R.id.item_gridview);
tv.setText(items.get(position).first);
return rowView;
}
}
class AdapterItem {
String first;
AdapterItem(String first) {
this.first = first;
}
}
}
gridview_item.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" >
<TextView
android:id="#+id/item_gridview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="0dp"
android:paddingEnd="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="?android:attr/textColorPrimary"
/>
</LinearLayout>
CardView with GridView (recyclerview_item_gv)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:id="#+id/cv_gv"
android:layout_marginBottom="20dp"
>
<LinearLayout
android:id="#+id/lineralayout_gv_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:animateLayoutChanges="true">
<LinearLayout
android:id="#+id/linearlayout_gv_titlerow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="2dp"
android:weightSum="100">
<TextView
android:id="#+id/tv_gv_A"
android:layout_weight="90"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="?android:attr/textColorPrimary"
style="#android:style/TextAppearance.Medium" />
<TextView
android:id="#+id/tv_gv_expandcollapse"
android:importantForAccessibility="no"
android:clickable="true"
android:focusable="true"
android:layout_weight="10"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textColor="?android:attr/textColorPrimary"
style="#android:style/TextAppearance.Large" />
</LinearLayout>
<RelativeLayout
android:id="#+id/relativelayout_gv"
android:animateLayoutChanges="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<GridView
android:id="#+id/gv_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnWidth="100dp"
android:numColumns="auto_fit"
android:layout_marginBottom="20dp"
android:stretchMode="columnWidth" />
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
CardView with TextView (recyclerview_item_tv.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="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:id="#+id/cv_tv"
android:layout_marginBottom="20dp">
<LinearLayout
android:id="#+id/linearlayout_gv_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:animateLayoutChanges="true">
<LinearLayout
android:id="#+id/linearlayout_tv_titlerow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="2dp"
android:weightSum="100">
<TextView
android:id="#+id/tv_tv_A"
android:layout_weight="90"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="?android:attr/textColorPrimary"
style="#android:style/TextAppearance.Medium" />
<TextView
android:id="#+id/tv_tv_expandcollapse"
android:importantForAccessibility="no"
android:clickable="true"
android:focusable="true"
android:layout_weight="10"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textColor="?android:attr/textColorPrimary"
style="#android:style/TextAppearance.Large" />
</LinearLayout>
<RelativeLayout
android:id="#+id/relativelayout_tv"
android:animateLayoutChanges="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tv_B"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?android:attr/textColorPrimary"
style="#android:style/TextAppearance.Large" />
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Ok so I made a quick example of how to do it. This is how the Activity class I'm posting looks like, all items are in the same RecyclerView:
Bear in mind, it might not look like your code because I am trying to use (At least for me) best practices, and also shorten the amount of code and classes by containing a lot of things in the same class.
Here is the Activity:
public class RecyclerActivity extends AppCompatActivity {
RecyclerView recycler;
ArrayList<String> data;
RecyclerView.Adapter<ViewHolder> adapter;
private static final int ITEM_TYPE = 100;
private static final int HEADER_TYPE = 101;
private static final int HEADER_TYPE_2 = 102;
private static final int GRID_TYPE = 103;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler);
// find recycler,
recycler = findViewById(R.id.recycler);
// set the layout
recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
// init data,
data = new ArrayList<>();
data.add("Item A");
data.add("Item B");
data.add("Item C");
// create the adapter
adapter = createAdapter();
// set the adapter
recycler.setAdapter(adapter);
}
// creates the adapter,
private RecyclerView.Adapter<ViewHolder> createAdapter() {
return new RecyclerView.Adapter<ViewHolder>() {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int type) {
switch (type) {
case HEADER_TYPE:
// inflate the layout,
ViewHolder holderHeader1 = new ViewHolder(inflateHelper(R.layout.header, parent));
// set an on click to the view here to create only one object,
holderHeader1.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
return holderHeader1;
case HEADER_TYPE_2:
// inflate the layout,
ViewHolder holderHeader2 = new ViewHolder(inflateHelper(R.layout.header, parent));
// set an on click to the view here to create only one object,
holderHeader2.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
return holderHeader2;
case ITEM_TYPE:
// inflate the layout,
ViewHolder holderItem = new ViewHolder(inflateHelper(R.layout.item, parent));
// set an on click to the view here to create only one object,
holderItem.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
return holderItem;
case GRID_TYPE:
// inflate the layout,
ViewHolder holderGrid = new ViewHolder(inflateHelper(R.layout.grid, parent));
// set an on click to the view here to create only one object,
holderGrid.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
return holderGrid;
default:
// inflate the layout,
ViewHolder holderItemDefault = new ViewHolder(inflateHelper(R.layout.item, parent));
// set an on click to the view here to create only one object,
holderItemDefault.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
return holderItemDefault;
}
}
/**
* Keep the viewholder simple and the all the view finding here. This way you
* only have one viewholder.
*/
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) {
// go through the positions
switch (getItemViewType(position)) {
case HEADER_TYPE:
Button expandButton = viewHolder.itemView.findViewById(R.id.button);
expandButton.setText("Expand");
break;
case HEADER_TYPE_2:
Button collapseButton = viewHolder.itemView.findViewById(R.id.button);
collapseButton.setText("Collapse");
break;
case ITEM_TYPE:
// get the current item
String item = data.get(position - 3);
TextView title = viewHolder.itemView.findViewById(R.id.title);
title.setText(item);
break;
case GRID_TYPE:
break;
}
}
#Override
public int getItemCount() {
return data.size() + 3;
}
#Override
public int getItemViewType(int position) {
switch (position) {
case 0:
return HEADER_TYPE;
case 1:
return HEADER_TYPE_2;
case 2:
return GRID_TYPE;
default: return ITEM_TYPE;
}
}
};
}
private View inflateHelper(int resId, ViewGroup parent) {
return LayoutInflater.from(this).inflate(resId, parent, false);
}
// inner class for viewholder to use,
class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}
You might notice that I have used one ViewHolder. This is a pattern I believe we should adopt because it simplifies code so much more. You can find the views you need in the onBind method and thus get away with using one for all types of views.
Also I add the on click listener in the onCreateViewHolder because it is much more efficient to set it there, and it allows for the viewholder to not be onClick specific.
As I said, you can use as many types as you want, you just need to check for it, and set it at the right position.
Here are the layout files if you are interested:
Header
<?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="wrap_content"
android:padding="4dp"
android:gravity="center">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expand" />
</LinearLayout>
Item
<?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="wrap_content"
android:padding="16dp"
android:elevation="2dp"
android:layout_margin="16dp"
android:background="#drawable/rounded">
<TextView
android:id="#+id/title"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Item A"
android:textColor="#fff"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_chevron_right"
android:tint="#fff"/>
</LinearLayout>
Grid Layout (I cheated a bit here because I didn't see a reason to not hardcode vowels, although you might need to do it dynamically)
<?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:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:padding="16dp"
android:background="#drawable/rounded"
android:backgroundTint="#fff"
android:elevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="16dp"
android:text="French Vowels"
android:textStyle="bold"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/a"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="a"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
<TextView
android:id="#+id/e"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="e"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
<TextView
android:id="#+id/i"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="i"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/o"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="o"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
<TextView
android:id="#+id/u"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="u"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
<TextView
android:id="#+id/y"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="y"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
</LinearLayout>
</FrameLayout>
Rounded Drawable
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#222"/>
<corners android:radius="6dp"/>
</shape>
For anyone reading, if you happen to use Kotlin, consider using my small library which eliminates this recycler view boilerplate to a simple chain of functions:
https://github.com/Pfuster12/BoilerCycle

Not adequate behaviour of the BottomSheet

During the initialisation of the BottomView part of it appears in the bottom of the screen, when I'm trying to drag it by finger, it appears and then immediately disappear. How to fix it? Or how to make that all items of BottomSheet would appear in the screen, after the FloatActionButton is clicked?
Video of BottomSheet: https://www.youtube.com/watch?v=58bhlc-KfYA&feature=youtu.be
code of Activity:
public class FirstscreenActivity extends AppCompatActivity implements RecyclerItemClickListener.OnItemClickListener,
ItemAdapter.ItemListener {
private BottomSheetDialog mBottomSheetDialog;
BottomSheetBehavior behavior;
private ItemAdapter mAdapterItem;
private FloatingActionButton floatButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.front);
mList = (RecyclerView) findViewById(R.id.list);
mList.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getApplicationContext());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mList.addOnItemTouchListener(new RecyclerItemClickListener(this, this));
mList.setLayoutManager(mLayoutManager);
floatButton = (FloatingActionButton) findViewById(R.id.float_button);
floatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showBottomSheetDialog();
}
});
View bottomSheet = findViewById(R.id.bottom_sheet;
behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState) {
// React to state change
}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset) {
// React to dragging events
}
});
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapterItem = new ItemAdapter(createItems(), this);
recyclerView.setAdapter(mAdapterItem);
}
#Override
protected void onResume() {
super.onResume();
RecyclerViewAdapter adapter = (RecyclerViewAdapter) mList.getAdapter();
adapter.notifyDataSetChanged();
}
private void showBottomSheetDialog() {
if (behavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
mBottomSheetDialog = new BottomSheetDialog(this);
View view = getLayoutInflater().inflate(R.layout.sheet, null);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new ItemAdapter(createItems(), new ItemAdapter.ItemListener() {
#Override
public void onItemClick(Item item) {
if (mBottomSheetDialog != null) {
mBottomSheetDialog.dismiss();
}
}
}));
mBottomSheetDialog.setContentView(view);
mBottomSheetDialog.show();
mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mBottomSheetDialog = null;
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mAdapterItem.setListener(null);
}
public List<Item> createItems() {
ArrayList<Item> items = new ArrayList<>();
items.add(new Item(R.drawable.camera, "from new shoots"));
items.add(new Item(R.drawable.folder_multiple_image, "from ready images"));
return items;
}
#Override
public void onItemClick(Item item) {
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}
RecyclerView Adapter inside the BottomSheet:
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
private List<Item> mItems;
private ItemListener mListener;
public ItemAdapter(List<Item> items, ItemListener listener) {
mItems = items;
mListener = listener;
}
public void setListener(ItemListener listener) {
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setData(mItems.get(position));
}
#Override
public int getItemCount() {
return mItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView imageView;
public TextView textView;
public Item item;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
textView = (TextView) itemView.findViewById(R.id.textView);
}
public void setData(Item item) {
this.item = item;
imageView.setImageResource(item.getDrawableResource());
textView.setText(item.getTitle());
}
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onItemClick(item);
}
}
}
public interface ItemListener {
void onItemClick(Item item);
}
}
xml of Activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#118b0a"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/my_toolbar" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/float_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
android:src="#drawable/add_white" />
<android.support.design.widget.CoordinatorLayout
android:layout_width="0dp"
android:layout_height="0dp">
<LinearLayout
android:id="#+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:gravity="center"
android:orientation="vertical"
app:layout_behavior="#string/bottom_sheet_behavior">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:background="#fff" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
</RelativeLayout>
xml of RecyclerView item inside the BottomSheet:
<?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="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="16dp"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:gravity="center_vertical"
android:textColor="#787878"
android:textSize="22sp" />
</LinearLayout>
These two lines of code solved my problem:
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);

RecyclerView Not showing up in my app

i couldn't find whats wrong with my code.. RecyclerView not showing up when i run my app..
Thanks in advance.
Main Activity onCreate Method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_appbar);
toolbar=(Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavFragment drawerFragment = (NavFragment)
getSupportFragmentManager().findFragmentById(R.id.nav_frag);
drawerFragment.setUp(R.id.nav_frag, (DrawerLayout) findViewById(R.id.drawerLayout), toolbar);
listEvents= new ArrayList<>();
Parse.enableLocalDatastore(this);
Parse.initialize(this, "xxxxxxx", "xxxxxxxx");
//TEST PARSE
final TextView t =(TextView) findViewById(R.id.textView);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Test");
//query.whereEqualTo("playerName", "Dan Stemkoski");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> eventList, ParseException e) {
if (e == null) {
Log.d("Events", "Retrieved " + eventList.size() + " Events");
for (int i = 0; i < eventList.size(); i++) {
Events events = new Events();
events.setTitle((String) eventList.get(i).get("teststr"));
events.setId(String.valueOf( eventList.get(i).get("id")));
listEvents.add(events);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
eventAdapter= new EventAdapter(this);
eventAdapter.setEventList(listEvents);
eventsList=(RecyclerView)findViewById(R.id.list_events);
eventsList.setLayoutManager(new LinearLayoutManager(this));
eventsList.setAdapter(eventAdapter);
}
Event Adapter for the RecylerView :
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.ViewHolderEvents> {
private LayoutInflater layoutInflater;
private ArrayList<Events> listEvents= new ArrayList<>();
public EventAdapter(Context context){
layoutInflater=LayoutInflater.from(context);
}
public void setEventList(ArrayList<Events> listEvents){
this.listEvents=listEvents;
notifyItemRangeChanged(0,listEvents.size());
}
#Override
public ViewHolderEvents onCreateViewHolder(ViewGroup viewGroup, int i) {
View view=layoutInflater.inflate(R.layout.custom_event_row,viewGroup,false);
ViewHolderEvents viewHolder =new ViewHolderEvents(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolderEvents viewHolderEvents, int i) {
Events currentEvent= listEvents.get(i);
viewHolderEvents.title.setText(currentEvent.getTitle());
viewHolderEvents.id.setText(currentEvent.getId());
}
#Override
public int getItemCount() {
return listEvents.size();
}
static class ViewHolderEvents extends RecyclerView.ViewHolder{
private TextView title;
private TextView id;
public ViewHolderEvents(View itemView) {
super(itemView);
title=(TextView)itemView.findViewById(R.id.title);
id=(TextView)itemView.findViewById(R.id.description);
}
}
}
XML Layout which is been set as Layout for the RecylerView: activity_main_appbar :
<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"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/list_events"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_gravity="center" />
</FrameLayout>
<fragment
android:id="#+id/nav_frag"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_nav"
android:name="com.squaredbytes.eventlane.NavFragment"
tools:layout="#layout/fragment_nav" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Try to create and set your EventAdapter into your FindCallback.
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> eventList, ParseException e) {
if (e == null) {
Log.d("Events", "Retrieved " + eventList.size() + " Events");
for (int i = 0; i < eventList.size(); i++) {
Events events = new Events();
events.setTitle((String) eventList.get(i).get("teststr"));
events.setId(String.valueOf( eventList.get(i).get("id")));
listEvents.add(events);
}
eventAdapter = new EventAdapter(this);
eventAdapter.setEventList(listEvents);
eventsList.setAdapter(eventAdapter);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});

Categories

Resources