Android expandable textview on RecyclerView - android

I'm use recyclerview and holder adapter. This have textview and maxlines is 4. I want to if user click then expand again click then collapse.
My codes is working but i have an issue;
When i click textview this going to expanded work fine but when i was scroll to down list some textview is automatic expanded state(but i did not touch them).
XML:
<android.support.v7.widget.AppCompatTextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/uiPadding_4dp"
android:maxLines="4"/>
Holder:
private final List<Integer> listReadMore = new ArrayList<>();
public void onBind(final Holder holder, final int position) {
final Obj obj = getObj(position);
final int id = obj.id();
final String text = obj.text();
holder.text.post(new Runnable() {
#Override
public void run() {
if(holder.text.getLineCount() >= maxLine)
listReadMore.add(id);
}
});
holder.text.setText(Kit.doHtmlText(text));
holder.text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listReadMore.contains(id)){
ObjectAnimator animation = ObjectAnimator.ofInt(
holder.text,
"maxLines",
holder.text.getLineCount());
animation.setDuration(600);
animation.start();
listReadMore.remove(listReadMore.indexOf(id));
}else{
ObjectAnimator animation = ObjectAnimator.ofInt(holder.text, "maxLines", 4);
animation.setDuration(400);
animation.start();
listReadMore.add(id);
}
}
});
}
When i was use simplify code I'm having the same problem again..
holder.text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.text.setMaxLines(100);
}
});
I was use https://github.com/Manabu-GT/ExpandableTextView this api but have some issue on recyclerview.
I dont know what can i do..

Related

Recycler view item colour change repeating after scrolling

Recycler view item color change repeating after scrolling.
I used to change color at a particular position of the Recyclerview list. When scrolling occurs another item at the bottom has the same change. And it is repeating in pattern. How to resolve this?
holder.recycle_Listing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemListener.connectionClicked(v,position, itemtype);
holder.mainlayout.setBackgroundColor(Color.parseColor("#e927a4d1"));
}
});
The recycler view recycles the view in OnBindViewHolder.So when items are clicked it gets reflected in some other positions.To solve this. create a global SparseBooleanArray to store the clicked position.
private final SparseBooleanArray array=new SparseBooleanArray();
Then inside final viewholder add the clickListener and onClick store the position of the clicked item.
public class ViewHolder extends RecyclerView.ViewHolder {
public YOURVIEW view;
public ViewHolder(View v) {
super(v);
view = (YOURVIEW) v.findViewById(R.id.YOURVIEWID);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
array.put(getAdapterPosition(),true);
notifyDataSetChanged();
}
});
}
}
And in inside OnBindViewHolder,
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
if(array.get(position)){
holder.mainlayout.setBackgroundColor(Color.parseColor("#e927a4d1"));
}else{
holder.mainlayout.setBackgroundColor(UNSELECTEDCOLOR);
}
}
I think you can set your background color in void onBindViewHolder(VH holder, int position); such as
List<Integer> selectedPosition = new ArrayList(yourDataSize);
void onBindViewHolder(VH holder, int position){
if(selectedPosition.get(position) == 1){
holder.mainlayout.setBackgroundColor(Color.parseColor("#e927a4d1"));
}else {
holder.mainlayout.setBackgroundColor(normalColor);
}
//when the item clicked
selectedPosition.add(position,1);
}
That function returns relative position not absolute so when screen is scrolled position is replaced with a new value. use position from your list for the desired result.
It is due to recycling of viewholder of recycler view. Try this
It worked for me.
public ListViewHolder(View itemView) {
super(itemView);
this.setIsRecyclable(false);
}
try to implement this method in your adapter class, may be it's solve your problem
#Override
public void onViewRecycled(ViewHolderProduct holder) {
super.onViewRecycled(holder);
holder.mainlayout.removeAllViews();
}
Just saved every item keys in an array and that selected array also passed through my Adapter class. Even simple colour change works fine in this format. Here the code is changed as per my the requirement.
#Override
public void onBindViewHolder(final ICConversationHomeAddConnectionsAdapter.ViewHolder holder, final int position) {
JsonObject object = dataArray.get(position).getAsJsonObject();
if(selectedArray.contains(object.get("userkey").getAsString()))
{
GradientDrawable borCol = new GradientDrawable();
borCol.setCornerRadius(7);
borCol.setColor(Color.parseColor("#ffffff"));
borCol.setStroke(2, Color.parseColor("#60B9E1"));
holder.recycle_Listing.setBackgroundDrawable(borCol);
//holder.mainlayout.setBackgroundColor(Color.parseColor("#e927a4d1"));
}
else
{
GradientDrawable borCol = new GradientDrawable();
borCol.setCornerRadius(7);
borCol.setColor(Color.parseColor("#ffffff"));
borCol.setStroke(1, Color.parseColor("#e0e0e0"));
holder.recycle_Listing.setBackgroundDrawable(borCol);
//holder.mainlayout.setBackgroundColor(Color.parseColor("#f1f1f1"));
}
holder.profileName.setText(object.get("name").getAsString());
holder.recycle_Listing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.mainlayout.setSelected(!holder.mainlayout.isSelected());
if (holder.mainlayout.isSelected()) {
GradientDrawable borCol = new GradientDrawable();
borCol.setCornerRadius(7);
borCol.setColor(Color.parseColor("#ffffff"));
borCol.setStroke(2, Color.parseColor("#60B9E1"));
holder.recycle_Listing.setBackgroundDrawable(borCol);
// holder.mainlayout.setBackgroundColor(Color.parseColor("#11B5DA"));
} else {
GradientDrawable borCol = new GradientDrawable();
borCol.setCornerRadius(7);
borCol.setColor(Color.parseColor("#ffffff"));
borCol.setStroke(1, Color.parseColor("#e0e0e0"));
holder.recycle_Listing.setBackgroundDrawable(borCol);
// holder.mainlayout.setBackgroundColor(Color.parseColor("#f1f1f1"));
}
itemListener.connectionClicked(v,position, itemtype);
//holder.mainlayout.setBackgroundColor(Color.parseColor("#11B5DA"));
//holder.mainlayout.setBackgroundColor(Color.parseColor("#f1f1f1"));
}
});
}
This code works fine with no repeated colour change in recycler. If any queries feel free to ask via comments or chat
Recyclerview & Room Database in Kotlin.
in Activity: //to send position to Adapter
val putPosition = 5 // what you want to be position
Handler(Looper.getMainLooper()).postDelayed({
(Recyclerview.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(putPosition-1,0)
}, 1500)
//
//
// out of onCreate (for companion)
fun getVersePosition() = putPosition
in Adapter: // to get position from Activity
override fun onBindViewHolder(holder: Adapter.Holder, position: Int) {
val roomData = listData[position]
holder.setRoomData(roomData)
val activity : MainActivity.Companion = MainActivity
val getPosition : Int? = activity.companionMainActivity?.getVersePosition()
if (position == getPosition-1){
holder.itemView.setBackgroundColor(Color.parseColor("#AFB42B"))
} else {
holder.itemView.setBackgroundColor(Color.TRANSPARENT)
}
}
SparseBooleanArray() doesn't need
and bind doesn't need too.
But it's very important
holder.itemView.setBackgroundColor(Color.TRANSPARENT)
If omitted, repetition will occur.

Can a TextView inside LinearLayout container be collapsed and expand on Button click?

I can dynamically add the text fields in my LinearLayout container.
Now I need to collapse those added fields in click of the Button those added fields should get collapse with any label.
Can it be done? Below is the code that i can add the EditText dynamically.
txtHeading = (EditText)findViewById(R.id.heading);
buttonAdd = (Button)findViewById(R.id.add);
container = (LinearLayout)findViewById(R.id.container);
buttonAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0)
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.list_view, null);
LinearLayout linearLayout=(LinearLayout)findViewById(R.id.layout_icon_select);
TextView textOut = (TextView)addView.findViewById(R.id.textout);
textOut.setText(textIn.getText().toString());
textIn.setText(null);
Button buttonRemove = (Button)addView.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
((LinearLayout)addView.getParent()).removeView(addView);
}
});
container.addView(addView);
}}});
btnsave = (Button) findViewById(R.id.btn_save);
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What to insert here?
on click to save button in need to collapse all the textView Elements.
let us consider Heading is the label and it is named as Gender so if i added the options as male and female then after clicking the save button this should get collapsed under the Heading.
Based on what I'm kind of guessing that you want... I would create a custom view class based on a linear layout. Each having two edit texts.
Create and add this class to dynamically when the add button is pressed. When the save button is pressed, you can loop over the parent LinearLayout's children and then call a helper method to collapse the second edit text element.
To Loop over the parent and collapse children. Now the CustomElement and the collapseOptionField() call is custom code you must write.
LinearLayout parentLayout = findViewById(...);
for ( int i = 0; i < parentLayout.getChildCount(); i++ ) {
CustomElement ce = parentLayout.getChildAt(i);
ce.collapseOption();
}
Update
Custom class with collapse-able option:
public class TextWithOption extends LinearLayout {
EditText edit0;
EditText edit1;
public TextWithOption(Context context, AttributeSet attrs) {
this(context);
}
public TextWithOption(Context context) {
super(context);
View view = LayoutInflater.from(context).inflate(R.layout.edit_text_option, null);
edit0 = (EditText) view.findViewById(R.id.edit_text0);
edit1 = (EditText) view.findViewById(R.id.edit_text1);
addView(view);
}
public void collapseOption() {
edit1.setVisibility(View.GONE);
}
public void showOption() {
edit1.setVisibility(View.VISIBLE);
}
}
Activity code that will add new options and then collapse them:
final LinearLayout optionsLayout = (LinearLayout) findViewById(R.id.outer_layout);
Button addButton = (Button) findViewById(R.id.button_add);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextWithOption to = new TextWithOption(context);
optionsLayout.addView(to);
}
});
((Button) findViewById(R.id.button_save)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for ( int i = 0; i < optionsLayout.getChildCount(); i++ ) {
((TextWithOption)optionsLayout.getChildAt(i)).collapseOption();
}
}
});
public static void collapse(final View v) {
ScaleAnimation anim = new ScaleAnimation(1, 1, 1, 0);
v.startAnimation(anim);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
v.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
onclick of button write view.collapse
view equals to whatever view you want collapse

Clear Animation in ViewHolder's item RecyclerView

I am using RecyclerView and have some animation where I scaleup one of RelativeLayout in ViewHolder item.
Note: It is not the add/remove/insert animation. It starts when user interacts in ViewHolder item. Hence I am not using ItemAnimator here.
Animation works fine but it reappears (final state) in some random View item. I know it is due to reuse of items and I am clearing animation too but it didn't help.
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
Model model = getModelObject(position);
((Model) viewHolder.itemView).showItem(position);
}
I am doing this in showItem
relativeLayout.clearAnimation();
relativeLayout.setAnimation(null);
In onViewDetachedFromWindow
#Override
public void onViewDetachedFromWindow(ViewHolder holder) {
((ItemView) holder.itemView).clearAllAnimations();
super.onViewDetachedFromWindow(holder);
}
ClearAllAnimations
public void clearAllAnimations() {
for (RelativeLayout layout : layoutArray) {
optionLayout.clearAnimation();
optionLayout.setAnimation(null);
}
Here how I am animating the view
public AnimatorSet onDragStartAnimation(RelativeLayout group[]) {
AnimatorSet big = new AnimatorSet();
for (RelativeLayout relativeLayout : group) {
ObjectAnimator scaleXSmall = ObjectAnimator.ofFloat(relativeLayout, "scaleX", 1.0f, 0.85f);
ObjectAnimator scaleYSmall = ObjectAnimator.ofFloat(relativeLayout, "scaleY", 1.0f, 0.85f);
big.playTogether(scaleXSmall, scaleYSmall);
}
return big;
}
it is not working. RelativeLayout not resetting and appearing in scaledup state in some random View Item.
Update
I did small experiment: Set alpha animation on ImageView in ViewHolder item like this
Animation fadeInAnimation = AnimationUtils.loadAnimation(mContext, R.anim.fadein);
imageView.startAnimation(fadeInAnimation);
and used clear animation. imageView.clearAnimation(); it worked and ImageView was visible normal when next time ViewItem appears on the screen.
But same is not working if I do this
alphaAnimator = ObjectAnimator.ofFloat(centerImageView, "alpha", 1.0f, 0.5f);
alphaAnimator.start();
And to clear this
alphaAnimator.removeAllListeners();
alphaAnimator.cancel();
alphaAnimator.end();
this didn't work. Alpha animation remains in ViewHolder image item.
I solved the problem in this way. Everything works fine.
GroupsViewHolder - it is custom RecyclerView.ViewHolder
#Override
public void onViewAttachedToWindow(GroupsViewHolder holder) {
super.onViewAttachedToWindow(holder);
//here add animation
}
#Override
public void onViewDetachedFromWindow(GroupsViewHolder holder) {
//here clear animation
super.onViewDetachedFromWindow(holder);
}
By inspiring from crymson's answer from Crymson's answer I have made little easy and useful solution using tag method of View instead setting a boolean in complicated logic of your custom adapter.
#Override
public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
super.onViewDetachedFromWindow(holder);
if (holder.getItemViewType() == TYPE_AD)
((ViewHolderForAd) holder).ivStory.setTag(false);
}
public class ViewHolderForAd extends RecyclerView.ViewHolder {
private ImageView ivStory;
TextView tvName;
public ViewHolderForAd(View view) {
super(view);
ivStory = (ImageView) view.findViewById(R.id.ivStoryImage);
tvName = (TextView) view.findViewById(R.id.tvAppName);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos < 0) {
pos = (int) v.getTag();
}
customItemClickListener.onItemClicked(v, pos);
}
});
//ivStory.startAnimation(AnimationUtils.loadAnimation(context, R.anim.pulse_story));
ivStory.setTag(false); //Set default tag false to decrease risk of null
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
//...Your code...
if (!(boolean) holder1.ivStory.getTag()) {
holder1.ivStory.setTag(true);
holder1.ivStory.startAnimation(AnimationUtils.loadAnimation(context, R.anim.pulse_story));
}
//...Your code...//
}
You can use setTag(key, object) instead of setTag(object) if you already tagged something(like position) in your imageView. Hope this helps someone.
I solved it by doing reverse animation of all animators in onViewDetachedFromWindow.
#Override
public void onViewDetachedFromWindow(ViewHolder holder) {
if (holder.getItemViewType() == 1) ((MyItemView) holder.itemView).reverseAllAnimations();
}

CardView click event and focus at same time

I have one CardView with custom selector which include focus state to true
<android.support.v7.widget.CardView
android:id="#+id/cvColor"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="center"
android:layout_marginBottom="4dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp"
android:foreground="#drawable/card_color_size"
android:minHeight="50dp"
android:visibility="gone"
app:cardCornerRadius="3dp"
app:cardElevation="4dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true" >
My need is when I click on card it should be clicked as well as focused too. so I did something like this.
#Override
public void onBindViewHolder(final ViewHolderCard1 viewHolder,
final int position) {
viewHolder.size.setVisibility(View.VISIBLE);
viewHolder.tvSize.setText(size.get(position).get("size"));
viewHolder.size.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
posSize = position;
Toast.makeText(getApplicationContext(), "" + posSize,
Toast.LENGTH_SHORT).show();
viewHolder.size.setFocusableInTouchMode(true);
}
});
}
now when I click once of the item of RecycleView it works fine, both Toast and focus happens same time.
But as soon as I click next item it just like on first click card perform click event and on second it gets focus.
anyone has idea what should I do?
Try this code.
#Override
public void onBindViewHolder(final ViewHolderCard1 viewHolder,
int position) {
viewHolder.size.setVisibility(View.VISIBLE);
viewHolder.tvSize.setText(size.get(position).get("size"));
viewHolder.size.setOnClickListener(new Listener(position, viewHolder.size));
}
class Listener implements OnClickListener {
private int position;
private ImageView imageView;
private CardView cardview;
Listener(int position, CardView cardview) {
this.position = position;
this.imageView = imageView;
this.data = data;
}
#SuppressLint("UseValueOf")
#Override
public void onClick(View v) {
posSize = position;
Toast.makeText(getApplicationContext(), "" + posSize,
Toast.LENGTH_SHORT).show();
CardView.setFocusableInTouchMode(true);
}
}
I solved this few days back do I am posting here my answer if any one faeces this problem.
SparseBooleanArray did the trick in my case.
First of all declare SparseBooleanArray in your Adapter Class. and Initialize it in your constructor of adapter class.
private ArrayList<HashMap<String, String>> size;
public final SparseBooleanArray selectedItems;
public Size(ArrayList<HashMap<String, String>> title) {
this.size = title;
selectedItems = new SparseBooleanArray(size.size());
}
Now I use setSelected for focusing selected card. inside onBindViewHolder (or getView in case you are using BaseAdapter).
viewHolder.size.setSelected(selectedItems.get(position));
viewHolder.size.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
posSize = position;
if (selectedItems.size() == 0) {
selectedItems.put(position, true);
} else if (selectedItems.size() > 0) {
selectedItems.clear();
selectedItems.put(position, true);
}
notifyDataSetChanged();
}
});
Happy Coding.

Expandable list with RecyclerView?

It's possible to use expandable list items with new RecyclerView? Like ExpandableListView?
This is simple to do with the stock LayoutManagers, it all depends on how you manage your adapter.
When you want to expand a section you just add new items to your adapter after the header. Remember to call notifyItemRangeInserted when you do this. To collapse a section you simply remove the relevant items, and call notifyItemRangeRemoved(). For any data changes that are appropriately notified, the recycler view will animate the views. When adding items, an area to be filled with the new items is made, with the new items fading in. Removal is the opposite. All you need to do besides the adapter stuff is to style your views to convey the logical structure to the user.
Update: Ryan Brooks has now written an article on how to do this.
Get the sample code implementation from here
Set ValueAnimator inside onClick of ViewHolder
#Override
public void onClick(final View view) {
if (mOriginalHeight == 0) {
mOriginalHeight = view.getHeight();
}
ValueAnimator valueAnimator;
if (!mIsViewExpanded) {
mIsViewExpanded = true;
valueAnimator = ValueAnimator.ofInt(mOriginalHeight, mOriginalHeight + (int) (mOriginalHeight * 1.5));
} else {
mIsViewExpanded = false;
valueAnimator = ValueAnimator.ofInt(mOriginalHeight + (int) (mOriginalHeight * 1.5), mOriginalHeight);
}
valueAnimator.setDuration(300);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
view.getLayoutParams().height = value.intValue();
view.requestLayout();
}
});
valueAnimator.start();
}
Here is the final code
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mFriendName;
private int mOriginalHeight = 0;
private boolean mIsViewExpanded = false;
public ViewHolder(RelativeLayout v) {
super(v);
mFriendName = (TextView) v.findViewById(R.id.friendName);
v.setOnClickListener(this);
}
#Override
public void onClick(final View view) {
if (mOriginalHeight == 0) {
mOriginalHeight = view.getHeight();
}
ValueAnimator valueAnimator;
if (!mIsViewExpanded) {
mIsViewExpanded = true;
valueAnimator = ValueAnimator.ofInt(mOriginalHeight, mOriginalHeight + (int) (mOriginalHeight * 1.5));
} else {
mIsViewExpanded = false;
valueAnimator = ValueAnimator.ofInt(mOriginalHeight + (int) (mOriginalHeight * 1.5), mOriginalHeight);
}
valueAnimator.setDuration(300);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
view.getLayoutParams().height = value.intValue();
view.requestLayout();
}
});
valueAnimator.start();
}
}
https://github.com/gabrielemariotti/cardslib
This library has an implementation of an expandable list with a recyclerview (refer to the demo app under "CardViewNative" --> "List, Grid, and RecyclerView" --> "Expandable cards"). It also has a lot of other cool combinations of cards/lists.
Someone complained about that the above mentioned solution is not usable with a listview as expandable content. But there's a simple solution: create a listview and fill this listview manually with your rows.
Solution for the lazy ones: there's a simple solution if you don't want to change your code to much. Just manually use your adapter to create views and add them to the LinearLayout.
Here's the example:
if (mIsExpanded)
{
// llExpandable... is the expandable nested LinearLayout
llExpandable.removeAllViews();
final ArrayAdapter<?> adapter = ... // create your adapter as if you would use it for a ListView
for (int i = 0; i < adapter.getCount(); i++)
{
View item = adapter.getView(i, null, null);
// if you want the item to be selectable as if it would be in a default ListView, then you can add following code as well:
item.setBackgroundResource(Functions.getThemeReference(context, android.R.attr.selectableItemBackground));
item.setTag(i);
item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// item would be retrieved with:
// adapter.getItem((Integer)v.getTag())
}
});
llExpandable.addView(item);
}
ExpandUtils.expand(llExpandable, null, 500);
}
else
{
ExpandUtils.collapse(llExpandable, null, 500);
}
helper functions: getThemeReference
public static int getThemeReference(Context context, int attribute)
{
TypedValue typeValue = new TypedValue();
context.getTheme().resolveAttribute(attribute, typeValue, false);
if (typeValue.type == TypedValue.TYPE_REFERENCE)
{
int ref = typeValue.data;
return ref;
}
else
{
return -1;
}
}
helper class: ExpandUtils
Kavin Varnan postet already how to animate a layout...
But if you want to use my class, feel free to do so, I posted a gist: https://gist.github.com/MichaelFlisar/738dfa03a1579cc7338a
You can use ExpandableLayout that like a smooth expand/collapse animation CheckBox, so you can use it as CheckBox in ListView and RecyclerView.
https://github.com/KyoSherlock/ExpandableLayout
This is the sample code for what is mentioned by #TonicArtos to add and remove Items and to animate it while doing, this is taken from RecyclerView Animations and GitHub sample
1) Add Listener inside your onCreateViewHolder() to register for onClick
2) Create your custom OnClickListener inside your Adapter
private View.OnClickListener mItemListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v.findViewById(R.id.tvItems);
String selected = tv.getText().toString();
boolean checked = itemsList.get(recyclerView.getChildAdapterPosition(v)).isChecked();
switch (selected){
case "Item1":
if(checked){
deleteItem(v);
itemsList.get(recyclerView.getChildAdapterPosition(v)).setChecked(false);
}else {
addItem(v);
itemsList.get(recyclerView.getChildAdapterPosition(v)).setChecked(true);
}
break;
case "Item2":
if(checked){
deleteItem(v);
itemsList.get(recyclerView.getChildAdapterPosition(v)).setChecked(false);
}else {
addItem(v);
itemsList.get(recyclerView.getChildAdapterPosition(v)).setChecked(true);
}
break;
default:
//In my case I have checkList in subItems,
//checkItem(v);
break;
}
}
};
3) Add your addItem() and deleteItem()
private void addItem(View view){
int position = recyclerView.getChildLayoutPosition(view);
if (position != RecyclerView.NO_POSITION){
navDrawItems.add(position+1,new mObject());
navDrawItems.add(position+2,new mObject());
notifyItemRangeInserted(position+1,2);
}
}
private void deleteItem(View view) {
int position = recyclerView.getChildLayoutPosition(view);
if (position != RecyclerView.NO_POSITION) {
navDrawItems.remove(position+2);
navDrawItems.remove(position+1);
notifyItemRangeRemoved(position+1,2);
}
}
4) If your RecyclerViewAdapter is not in the same Activity as Recycler View, pass instance of recyclerView to the Adapter while creating
5) itemList is a ArrayList of type mObject which helps maintain states of item (Open/Close) , name, type of Item(subItems/mainItem) and set Theme based on values
public class mObject{
private String label;
private int type;
private boolean checked;
}

Categories

Resources