Reputation: 191
I have two view holders in my custom adapter say
ViewHolder1 at position 0 ViewHolder2 at position 1
Currently with view is perfectly fine.
Now i have button in MainActivity. I want to do something like this in layman's term
On 1st click, it should hide the ViewHolder1 at position 0 and it should shift ViewHolder2 upwards. On 2nd click, it should view the Viewholder1 at position 0 and shift ViewHolder2 downward.
How do i achieve this ?
Upvotes: 2
Views: 832
Reputation: 4035
Maybe change the visibility of the whole item view to GONE or VISIBLE might help.
I don't know if it works, but in theory it might work (cause you don't seem to want to remove items from the datasource).
This is just to give you an idea on what you might do.
Use interface:
public interface itemVisibilityListener{
void itemVisibility(int position,int visibility);
}
In activity:
class MyActivity extends Activity implements itemVisibilityListener{
private int visible = View.VISIBLE;
private int gone = View.GONE;
private boolean firstItemVisible=true;
private MyAdapter adapter;
........
//on create
adapter.setItemVisibilityListener(this);
//when button clicked
button.setOnClickListener(new....{
if(firstItemVisible){
adapter.hideItem1(true);
}else{
adapter.hideItem1(false);
}
});
//this callback gives you feedback on visibility of first item
@override
public void itemVisibility(int position , int visibility){
button.setEnabled(true);
if(position==0 && visibility==visible){
//item of position 0 is visible
firstItemVisible=true;
}else if(position==0 && visibility==gone){
//item of position 0 is not visible
firstItemVisible=false;
}
}
}
In your adapter:
class MyAdapter extends .......{
private int visible = View.VISIBLE;
private int gone = View.GONE;
private boolean hide = false;
private itemVisibilityListener listener;
public void hideItem1(boolean hide){
this.hide=hide;
this.notifyDataSetChanged();
}
public void setItemVisibilityListener(itemVisibilityListener listener){
this.listener=listener;
}
.........
//on bind view holder
//this is your logic for handling multiple viewholders
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int postion){
if(holder.getItemViewType == FIRST_ITEM_TYPE){
//item 1 binding
if(hide){
holder.itemView.setVisibility(gone);
listener.itemVisibility(0,gone);
}else{
holder.itemView.setVisibility(visible);
listener.itemVisibility(0,visible);
}
}else if(holder.getItemViewType == SECOND_ITEM_TYPE){
//item 2 binding......
}
}
}
Upvotes: 1
Reputation: 29260
If you data is represented in a list like this,
data = mutableListOf<BaseClass>(item1, item2)
then you can remove the 1st viewholder by updating your data and notifying your adapter
data.remove(0)
adapter.notifyItemRemoved(0)
then when you want to add it again, you do
data.add(0, item1)
adapter.notifyItemInserted(0)
See this for reference.
Upvotes: 0