how to proper animate (expand and collapse) a textview with multiple lines - android

I have a recycle view with two TextViews. One is showed and the other is invisible (gone). When I tap an expand button the second textview became visible with a smooth animation. When I collapse the textview using the setVisible(GONE) method the textview is not collapsing using an animation.
I am using the following layout for the adapter item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:animateLayoutChanges="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fafafa"
android:orientation="horizontal"
android:paddingTop="8dp"
android:paddingBottom="8dp" >
<include
android:id="#+id/questionNumberTV"
layout="#layout/circular_step_number" />
<LinearLayout
android:layout_marginLeft="4dp"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="22sp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:paddingTop="4dp"
android:paddingBottom="4dp"
android:maxLines="2"
tools:text="Léon: The Professional sa sa saddsa das" />
<LinearLayout
android:id="#+id/expandContainer"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical">
<TextView
android:visibility="gone"
android:id="#+id/sub_item_genre"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Genre: Crime, Drama, Thriller"
/>
</LinearLayout>
</LinearLayout>
<ImageView
android:layout_marginLeft="24dp"
android:id="#+id/expandOrColapse"
android:src="#drawable/ic_chevron_down_black_24dp"
android:layout_width="24dp"
android:layout_height="24dp" />
</LinearLayout>
And the Adapter java code is below:
import android.animation.LayoutTransition;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import static android.view.View.GONE;
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.RecViewHolder> {
private static final String TAG = RecAdapter.class.getName();
private List<Movie> list;
private int lastExpandedMoviePosition = -1;
public RecAdapter(List<Movie> list) {
this.list = list;
}
#Override
public RecViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie, parent, false);
return new RecViewHolder(view);
}
#Override
public void onBindViewHolder(RecViewHolder holder, int position) {
holder.bindBean(list.get(position));
}
#Override
public int getItemCount() {
return list == null ? 0 : list.size();
}
public class RecViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private View questionNumberTV;
private TextView title;
private TextView genre;
private ImageView expandOrColapseIV;
private LinearLayout expandContainer;
public RecViewHolder(View itemView) {
super(itemView);
expandContainer = (LinearLayout) itemView.findViewById(R.id.expandContainer);
questionNumberTV = itemView.findViewById(R.id.questionNumberTV);
title = itemView.findViewById(R.id.item_title);
genre = itemView.findViewById(R.id.sub_item_genre);
expandOrColapseIV = itemView.findViewById(R.id.expandOrColapse);
expandOrColapseIV.setOnClickListener(this);
}
private void bindBean(Movie movie) {
boolean expanded = movie.isExpanded();
//questionNumberTV.setText((getAdapterPosition() + 1) + ".");
genre.setVisibility(expanded ? View.VISIBLE : GONE);
genre.setText("Genre: " + movie.getGenre());
if (movie.isAnswered()) {
expandContainer.getLayoutTransition().setDuration(800);
expandContainer.getLayoutTransition().enableTransitionType(LayoutTransition.CHANGING);
expandContainer.getLayoutTransition().setAnimateParentHierarchy(true);
if (expanded) {
expandOrColapseIV.setImageDrawable(ContextCompat.getDrawable(itemView.getContext(), R.drawable.ic_chevron_up_black_24dp));
// setHeightChangeAnimation(expandContainer);
} else {
// collapse(expandContainer);
expandOrColapseIV.setImageDrawable(ContextCompat.getDrawable(itemView.getContext(), R.drawable.ic_chevron_down_black_24dp));
}
}
title.setText(movie.getTitle());
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.expandOrColapse) {
lastExpandedMoviePosition = getAdapterPosition();
list.get(lastExpandedMoviePosition).setExpanded(!list.get(lastExpandedMoviePosition).isExpanded());
list.get(lastExpandedMoviePosition).setAnswered(true);
notifyItemChanged(lastExpandedMoviePosition);
}
}
}
}
Best Regards,
Aurelian

I found the answer here (Hermann Klecker post)
Android: get height of a view before it´s drawn
private void expandView( final View view ) {
view.setVisibility(View.VISIBLE);
LayoutParams parms = (LayoutParams) view.getLayoutParams();
final int width = this.getWidth() - parms.leftMargin - parms.rightMargin;
view.measure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
final int targetHeight = view.getMeasuredHeight();
view.getLayoutParams().height = 0;
Animation anim = new Animation() {
#Override
protected void applyTransformation( float interpolatedTime, Transformation trans ) {
view.getLayoutParams().height = (int) (targetHeight * interpolatedTime);
view.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
};
anim.setDuration( ANIMATION_DURATION );
view.startAnimation( anim );
}

Related

how can i set gravity to right for row recyclerview

I want to set gravity to right in my recyclerview
,I set to right gravity for all layout but when horizontal recyclerview has one row, it do not set gravity to right
see picture to understand me picture
I want red circle in picture set gravity to right.
my CityDetailACT activity:
package safarkon.com.safarkon.cityDetail;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import java.util.ArrayList;
import safarkon.com.safarkon.R;
public class CityDetailACT extends AppCompatActivity {
private RecyclerViewDataAdapter rAdapterBazar;
ArrayList<SectionDataModelRecyclerModel> allSampleData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.city_detail_act);
allSampleData = new ArrayList<SectionDataModelRecyclerModel>();
rvListBazar.setHasFixedSize(true);
rvListBazar.setNestedScrollingEnabled(false);
rAdapterBazar = new RecyclerViewDataAdapter(CityDetailACT.this, allSampleData);
rvListBazar.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
rvListBazar.setAdapter(rAdapterBazar);
createDummyData();
}
public void createDummyData() {
for (int i = 2; i <= 8; i++) {
SectionDataModelRecyclerModel dm = new SectionDataModelRecyclerModel();
String cat = null;
if (i == 1){
//cat = "بدانید";
dm.setHeaderTitle("هر آنچه درمورد "+city+" باید بدانید");
}else if (i == 2){
cat = "بازار";
dm.setHeaderTitle("بازارهای "+city);
}else if (i == 3){
cat = "دیدنی";
dm.setHeaderTitle("معرفی مکانهای گردشگری "+city);
}else if (i == 4){
cat = "تاریخی";
dm.setHeaderTitle("دیدنی های تاریخی "+city);
}else if (i == 5){
cat = "پارک";
dm.setHeaderTitle("پارک های "+city);
}else if (i == 6){
cat = "مسجد";
dm.setHeaderTitle("مسجدها و امام زاده های "+city);
}else if (i == 7){
cat = "موزه";
dm.setHeaderTitle("موزه های "+city);
}else if (i == 8){
cat = "مدرسه";
dm.setHeaderTitle("مدرسه های "+city);
}
ArrayList<RecyclerModel> singleItem = new ArrayList<RecyclerModel>();
LoadData.firstLoadData(this,rAdapterBazar,singleItem,rvListBazar);
dm.setAllItemsInSection(singleItem);
allSampleData.add(dm);
}
}
}
RecyclerViewDataAdapter:
package safarkon.com.safarkon.cityDetail;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import safarkon.com.safarkon.R;
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {
private ArrayList<SectionDataModelRecyclerModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<SectionDataModelRecyclerModel> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_row_nested_list, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String sectionName = dataList.get(i).getHeaderTitle();
ArrayList singleSectionItems = dataList.get(i).getAllItemsInSection();
itemRowHolder.itemTitle.setText(sectionName);
RecyclerAdapter itemListDataAdapter = new RecyclerAdapter(singleSectionItems,"a",mContext);
itemRowHolder.recycler_view_list.setHasFixedSize(true);
itemRowHolder.recycler_view_list.setItemViewCacheSize(20);
itemRowHolder.recycler_view_list.setDrawingCacheEnabled(true);
itemRowHolder.recycler_view_list.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
itemRowHolder.recycler_view_list.setNestedScrollingEnabled(false);
itemRowHolder.recycler_view_list.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
itemRowHolder.recycler_view_list.setAdapter(itemListDataAdapter);
itemRowHolder.recycler_view_list.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, true));
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle;
protected RecyclerView recycler_view_list;
protected TextView txMore;
public ItemRowHolder(View view) {
super(view);
this.itemTitle = view.findViewById(R.id.itemTitle);
this.recycler_view_list =view.findViewById(R.id.recycler_view_list);
this.txMore= view.findViewById(R.id.txMore);
}
}
}
RecyclerAdapter:
package safarkon.com.safarkon.cityDetail;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import safarkon.com.safarkon.R;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private ArrayList<RecyclerModel> recyclerModels; // this data structure carries our title and description
Context c;
String rowLayoutType;
int width;
public RecyclerAdapter(ArrayList<RecyclerModel> recyclerModels,String rowLayoutType, Context c) {
this.recyclerModels = recyclerModels;
this.rowLayoutType = rowLayoutType;
this.c = c;
}
public RecyclerAdapter(ArrayList<RecyclerModel> recyclerModels,String rowLayoutType, Context c,int width) {
this.recyclerModels = recyclerModels;
this.rowLayoutType = rowLayoutType;
this.c = c;
this.width = width;
}
#Override
public RecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.row_city_detail, parent, false));
}
#Override
public void onBindViewHolder(final RecyclerAdapter.MyViewHolder holder,final int position) {
Picasso.with(c)
.load(recyclerModels.get(position).getPicture())
.resize(width,0)
.into(holder.imageView);
holder.tx_onvan.setText(recyclerModels.get(position).getOnvan());
holder.tx_position.setText(recyclerModels.get(position).getPosition());
holder.ratingBar.setRating((float)recyclerModels.get(position).getRate());
holder.txCountRateAndComment.setText("( "+recyclerModels.get(position).getCountRateAndComment() + " نظر" + " )");
}
#Override
public int getItemCount() {
return recyclerModels.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView txCountRateAndComment;;
TextView tx_onvan;
TextView tx_position;
ImageView imageView;
SimpleRatingBar ratingBar;
MyViewHolder(View view) {
super(view);
tx_onvan= itemView.findViewById(R.id.nameTxt);
tx_position= itemView.findViewById(R.id.txPostion);
imageView = itemView.findViewById(R.id.imageView2);
ratingBar= itemView.findViewById(R.id.simpleRatingBar);
txCountRateAndComment = itemView.findViewById(R.id.txCountRateAndComment);
}
}
}
city_detail_act:
<?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"
android:orientation="vertical"
android:gravity="top"
>
<android.support.v7.widget.Toolbar
android:id="#+id/tolbar_story"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#66cc66"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:gravity="center"
android:orientation="horizontal"
tools:layout_editor_absoluteX="16dp">
<ImageView
android:id="#+id/imgTooTitlelbarMainActf"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/adamak" />
<ImageView
android:id="#+id/imgTooTitlelbarMainAct"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="180dp"
android:layout_marginLeft="180dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="181dp"
android:layout_marginRight="181dp"
android:layout_marginBottom="3dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/title" />
<ImageView
android:id="#+id/imgNavigationView"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp"
android:adjustViewBounds="false"
android:scaleType="centerInside"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/dot" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.Toolbar>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="26dp"
android:layout_marginLeft="13dp"
android:layout_marginRight="13dp"
android:layout_marginBottom="12dp"
android:gravity="right"
android:orientation="horizontal">
<TextView
android:id="#+id/txMore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/adobearabicbold"
android:text="مشاهده همه..."
android:textSize="12sp"
/>
<TextView
android:id="#+id/txYHinCityDetail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:fontFamily="#font/adobearabicbold"
android:text="هر آنچه درمورد قم باید بدانید"
android:textSize="24sp" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/rvListBazar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
I want set gravity to right when horizontal recyclerview has only one row,
because when horizontal recyclerview has more one row it gravity set to right
,How can i do it?
In your RecyclerViewDataAdapter ,set the last parameter of the setLayotManager to false and if that does not work , set LinearLayoutManager.setStatckFromEnd property to true

android recyclerview adapter progressbar not show

Refresh the progress bar multiple times not to show!
I am refreshing the data. This progress is not accurate. What I want is to show progress correctly every time I refresh.
Refresh the progress bar multiple times not to show!
I am refreshing the data. This progress is not accurate. What I want is to show progress correctly every time I refresh.
#demo
activity
package com.hjyt.youmi.testdemo;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import androi
d.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private RecyclerView mRecyclerView;
private Button mBtn;
private List<String> mDataList = new ArrayList<>();
private RecyclerViewAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
for (int i = 0; i < 10; i++) {
mDataList.add(String.valueOf(i));
}
mRecyclerView = findViewById(R.id.recycler_view);
mBtn = findViewById(R.id.btn_notify);
mBtn.setOnClickListener(this);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new RecyclerViewAdapter();
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_notify:
mAdapter.notifyDataSetChanged();
break;
}
}
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ProgressViewHolder> {
#Override
public ProgressViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = getLayoutInflater().inflate(R.layout.item_progress_layout, parent, false);
return new ProgressViewHolder(view);
}
#Override
public void onBindViewHolder(ProgressViewHolder holder, int position) {
setColors(holder.progressBar, Color.WHITE, Color.RED);
java.util.Random r = new java.util.Random();
holder.progressBar.setProgress(r.nextInt(100));
holder.textView.setText("position: " + position + "\n progress: " + holder.progressBar.getProgress());
}
#Override
public int getItemCount() {
return mDataList.size();
}
private void setColors(ProgressBar progressBar, int backgroundColor, int progressColor) {
//Background
ClipDrawable bgClipDrawable = new ClipDrawable(new ColorDrawable(backgroundColor), Gravity.LEFT, ClipDrawable.HORIZONTAL);
bgClipDrawable.setLevel(10000);
//Progress
ClipDrawable progressClip = new ClipDrawable(new ColorDrawable(progressColor), Gravity.LEFT, ClipDrawable.HORIZONTAL);
//Setup LayerDrawable and assign to progressBar
Drawable[] progressDrawables = {bgClipDrawable, progressClip, progressClip};
LayerDrawable progressLayerDrawable = new LayerDrawable(progressDrawables);
progressLayerDrawable.setId(0, android.R.id.background);
progressLayerDrawable.setId(1, android.R.id.secondaryProgress);
progressLayerDrawable.setId(2, android.R.id.progress);
progressBar.setProgressDrawable(progressLayerDrawable);
}
class ProgressViewHolder extends RecyclerView.ViewHolder {
ProgressBar progressBar;
TextView textView;
ProgressViewHolder(View itemView) {
super(itemView);
progressBar = itemView.findViewById(R.id.progress);
textView = itemView.findViewById(R.id.tv_desc);
}
}
}
}
activity xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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="com.hjyt.youmi.testdemo.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/btn_notify"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:id="#+id/btn_notify"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="更新数据"
android:textColor="#android:color/white"
android:background="#color/colorPrimary"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
adapter xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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">
<TextView
android:id="#+id/tv_desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<ProgressBar
android:id="#+id/progress"
style="#style/Base.Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="0dp"
android:layout_height="15dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:max="100"
android:progress="50"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_desc"/>
<View
android:layout_width="0dp"
android:layout_height="1px"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#android:color/darker_gray"
app:layout_constraintTop_toBottomOf="#+id/progress"/>
</android.support.constraint.ConstraintLayout>
you can use below methods to show and hide progress bar :
public static void showProgress(String message, Context context, boolean cancellable) {
if (context == null)
return;
if (checkProgressOpen())
return;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage(message == null ? "Please wait..." : (message));
dialog.setCancelable(cancellable);
try {
dialog.show();
} catch (Exception e) {
// catch exception for activity paused and dialog is going to be
// show.
}
}
public static boolean checkProgressOpen() {
if (dialog != null && dialog.isShowing())
return true;
else
return false;
}
public static void cancelProgress() {
if (checkProgressOpen()) {
try {
dialog.dismiss();
} catch (Exception e) {
}
dialog = null;
}
}
put this code in utility file , and use it wherever you need it..you can pass your message in arguments also
I've solved it myself and I don't need a progressbar to use a View and backgroud.
private void setColors(View viewBg, View view, int progressColor, int progress) {
int width = viewBg.getWidth();
int progress1 = width / 100;
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) view.getLayoutParams();
params.width = progress1 * progress;
view.setLayoutParams(params);
view.setBackgroundColor(progressColor);
}

GridView item looks not as expected - Android

I try to use a GridView object in a specific fragment in my app.
I created a layout file for the grid item and in the layout editor, the preview image looks good, as expected.
The problem arises when I run the app in my emulator. The whole item layout gets shrinked and the image I put in the middle suddenly jumps to the top of the layout.
Screenshot of the layout editor:
https://i.gyazo.com/8ed96ed19719a578388cc48aba6829f8.png
Screenshot of the emulator:
https://i.gyazo.com/cca0a32b3d102025df5d5369dc7c0efc.png
Here is the xml code for the fragment:
<?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">
<GridView
android:id="#+id/documents_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:columnWidth="#dimen/document_grid_item_width"
android:gravity="center"
android:horizontalSpacing="0dp"
android:verticalSpacing="0dp"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform" />
<RelativeLayout
android:id="#+id/empty_view_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/empty_view_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:src="#drawable/recent_empty_view" />
<ImageView
android:id="#+id/empty_view_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/empty_view_image"
android:layout_below="#+id/empty_view_image"
android:layout_marginEnd="7dp"
android:scaleX="0.75"
android:scaleY="0.75"
android:src="#drawable/empty_view_arrow" />
</RelativeLayout>
</RelativeLayout>
Here is the item layout xml code:
<?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:layout_width="#dimen/document_grid_item_width"
android:layout_height="#dimen/document_grid_item_height"
android:gravity="center"
android:orientation="vertical"
android:weightSum="1">
<FrameLayout
android:id="#+id/draft_frame"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.9"
android:background="#drawable/document_grid_item_bg"
android:focusable="true"
android:foreground="?android:selectableItemBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/draft_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/draft_icon" />
<ImageView
android:id="#+id/draft_more_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginTop="5dp"
app:srcCompat="#drawable/ic_more" />
</RelativeLayout>
</FrameLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
android:layout_weight="0.1">
<TextView
android:id="#+id/draft_date_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="20 May 17"
android:textSize="11sp" />
</RelativeLayout>
</LinearLayout>
Here is the adapter code:
package com.silverfix.dgdeditor.adapters;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.silverfix.dgdeditor.R;
import com.silverfix.dgdeditor.utils.DocumentPack;
import com.silverfix.dgdeditor.utils.views.ViewClickListener;
import com.silverfix.dgdeditor.utils.views.ViewLongClickListener;
import java.util.List;
/**
* Created by David on 14/05/2017.
*/
public class DraftsGridAdapter extends BaseAdapter {
// Listeners
private ViewClickListener clickListener;
private ViewLongClickListener longClickListener;
private Activity context;
private List<DocumentPack> dataSet;
private int clickedItemPos = -1;
public DraftsGridAdapter(Activity context, List<DocumentPack> dataSet) {
this.context = context;
this.dataSet = dataSet;
}
public void setClickedItemPosition(int clickedItemPos) {
this.clickedItemPos = clickedItemPos;
}
public int getClickedItemPosition() {
return clickedItemPos;
}
public void setClickListener(ViewClickListener clickListener) {
this.clickListener = clickListener;
}
public void setLongClickListener(ViewLongClickListener longClickListener) {
this.longClickListener = longClickListener;
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public Object getItem(int position) {
return dataSet.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final DocumentPack pack = dataSet.get(position);
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.draft_grid_item, null);
DraftViewHolder viewHolder = new DraftViewHolder(context, convertView);
convertView.setTag(viewHolder);
}
// Instance of a view holder from the tag of the convertView
DraftViewHolder viewHolder = (DraftViewHolder) convertView.getTag();
// Set the adapter position to the current view holder
viewHolder.setAdapterPosition(position);
// Bind the click listeners to the root view of the view holder
// viewHolder.bindClick(clickListener);
// viewHolder.bindLongClick(longClickListener);
// Bind the data to the view holder
viewHolder.bindData(pack);
return convertView;
}
private class DraftViewHolder implements View.OnCreateContextMenuListener {
private View.OnClickListener clickListener;
private View.OnLongClickListener onLongClickListener;
private View rootView;
private ImageView moreButton;
private TextView date;
private int position;
public DraftViewHolder(final Activity context, final View rootView) {
this.rootView = rootView;
date = (TextView) rootView.findViewById(R.id.draft_date_tv);
moreButton = (ImageView) rootView.findViewById(R.id.draft_more_button);
context.registerForContextMenu(rootView);
rootView.setOnCreateContextMenuListener(this);
moreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.openContextMenu(rootView);
setClickedItemPosition(position);
}
});
}
void setAdapterPosition(int position) {
this.position = position;
}
void bindClick(final ViewClickListener clickListener) {
this.clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
clickListener.onClick(position);
}
};
rootView.setOnClickListener(this.clickListener);
}
void bindLongClick(final ViewLongClickListener longClickListener) {
this.onLongClickListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
longClickListener.onLongClick(position);
return false;
}
};
rootView.setOnLongClickListener(this.onLongClickListener);
}
void bindData(DocumentPack draft) {
String formatDate = draft.getFormattedDate();
date.setText(formatDate);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
}
}
}
This worked for me, You can try...
`<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp" >
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="3"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="10dp" />
`
If this don't work you can also try to use android:stretchMode="columnWidth"

Android Master-Detail Application

I am trying to achieve the following -
"A master-detail two pane flow and the datasource in JSON will be fetched via volley".
My struggle is that I do not know how to transfer data when clickEvent() occured on Master Panel.
I have followed a few tutorials such as
http://mobileappdocs.com/android.html
http://www.techotopia.com/index.php/An_Android_Master/Detail_Flow_Tutorial
I still didn't get that part.
Is it because I am using the default master-detail layout from Android Studio in which only the right(detail) panel is Fragment and the left is not.
Should both the panels need to be Fragments?
My Codes and Progress : I have already done the layouts and I am struggling with the behind Java codes.
guest_list.xml
<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"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
android:showDividers="none"
tools:context="awesome.pyie.com.finalapp.GuestListActivity">
<!--
This layout is a two-pane layout for the Guests
master/detail flow.
-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/AppDarkGrey">
<SearchView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:id="#+id/searchView"
android:background="#color/AppLightGrey"
android:iconifiedByDefault="false"
android:queryHint="Search">
</SearchView>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/guest_list"
android:name="awesome.pyie.com.finalapp.GuestListFragment"
android:layout_width="308dp"
android:layout_height="match_parent"
app:layoutManager="LinearLayoutManager"
tools:context="awesome.pyie.com.finalapp.GuestListActivity"
tools:listitem="#layout/guest_list_content" />
</LinearLayout>
<FrameLayout
android:background="#color/AppLightGrey"
android:id="#+id/guest_detail_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/add_mid_one"
android:id="#+id/imageView"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="onClick"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Add Guest"
android:textColor="#color/AppWhite"
android:id="#+id/textView"
android:layout_gravity="center"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</FrameLayout>
guest_list_content.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/display1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#color/AppDarkGrey"> <!--Slave Layout-->
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/logo"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
app:civ_border_width="2dp"
app:civ_border_color="#83848A"/>
<TextView
android:id="#+id/id"
android:textColor="#color/AppWhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:layout_marginRight="10dp"
android:layout_alignTop="#+id/profile_image"
android:layout_alignStart="#+id/content" />
<TextView
android:id="#+id/content"
android:textColor="#color/AppBlue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:layout_marginLeft="#dimen/text_margin"
android:layout_marginRight="#dimen/text_margin"
android:layout_alignBottom="#+id/profile_image"
android:layout_toEndOf="#+id/profile_image"
android:layout_marginStart="26dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/AppTime"
android:text="5:58pm"
android:layout_marginRight="10dp"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true" />
<View android:background="#color/AppLightGrey" android:layout_width="fill_parent" android:layout_height="1dip" />
MyListActivity (Contains Pop Up Dialog Please ignore that Part)
package awesome.pyie.com.finalapp;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.SearchView;
import android.util.DisplayMetrics;
import android.view.View.OnClickListener;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Dialog;
import android.widget.Toast;
import org.w3c.dom.Text;
import awesome.pyie.com.finalapp.dummy.DummyContent;
import java.util.List;
public class GuestListActivity extends AppCompatActivity {
private boolean mTwoPane;
final Context context = this;
//API END POINT
public static final String JSON_URL = "*******";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guest_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Toolbar title Removed
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.findViewById(R.id.textView2).setVisibility(View.INVISIBLE);
toolbar.findViewById(R.id.addTop).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.add_user_dialog);
dialog.show();
//Calculate Device Width and height
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
Window window = dialog.getWindow();
window.setLayout((int)(dpWidth), (int)((dpHeight)+50));
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
TextView cancelText = (TextView) dialog.findViewById(R.id.textView2);
cancelText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
View recyclerView = findViewById(R.id.guest_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
if (findViewById(R.id.guest_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
toolbar.findViewById(R.id.textView2).setVisibility(View.VISIBLE);
}
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.guest_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
final ImageView imageView =(ImageView)findViewById(R.id.imageView);
final TextView textView = (TextView)findViewById(R.id.textView);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
//Code Here
imageView.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
//Ends Here
Bundle arguments = new Bundle();
arguments.putString(GuestDetailFragment.ARG_ITEM_ID, holder.mItem.id);
GuestDetailFragment fragment = new GuestDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.guest_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, GuestDetailActivity.class);
intent.putExtra(GuestDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
imageView.setOnClickListener(new View.OnClickListener() {
//Start new list activity
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.add_user_dialog);
dialog.show();
//Calculate Device Width and height
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
Window window = dialog.getWindow();
window.setLayout((int)(dpWidth), (int)((dpHeight)+50));
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
TextView cancelText = (TextView) dialog.findViewById(R.id.textView2);
cancelText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
}); //Add Button Function - will display the add page
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
If you guys want me to post any codes please let me know. Thanks in advanced!

RecyclerView Showing weird behavior on expanding CardView Android

<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingTop="#dimen/activity_horizontal_margin"
android:background="#android:color/transparent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/string_for_newsletter"
android:paddingLeft="16dp"
android:id="#+id/textQuestion"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/bookmark_star"
android:layout_alignParentRight="true"
android:background="#android:color/transparent"
android:layout_alignParentBottom="true"
android:id="#+id/bookmarkButton"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/textQuestion"
android:text="answer"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:textColor="#00ff00"
android:visibility="gone"
android:id="#+id/textAnswer"/>
</RelativeLayout>
this is my layout for card view
and below is the code for RecyclerView Adapter
package com.example.user_2.tcc_app.QuestionAnswer;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import com.example.user_2.tcc_app.R;
/**
* Created by USER-2 on 23-Feb-15.
*/
public class QuestionAnswerAdapter extends RecyclerView.Adapter<QuestionAnswerAdapter.QuestionAnswerAdapterViewHolder>{
int length;
int layout_id;
public long item_id;
public QuestionAnswerAdapter(int length, int id_for_layout){
this.length = length;
this.layout_id = id_for_layout;
}
#Override
public QuestionAnswerAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View root = LayoutInflater.from(parent.getContext()).inflate(layout_id, parent, false);
QuestionAnswerAdapterViewHolder questionAnswerAdapterViewHolder = new QuestionAnswerAdapterViewHolder(root);
return questionAnswerAdapterViewHolder;
}
#Override
public void onBindViewHolder(final QuestionAnswerAdapterViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return length;
}
public class QuestionAnswerAdapterViewHolder extends RecyclerView.ViewHolder{
TextView textQuestion;
ImageButton bookmarkButton;
TextView textAnswer;
public QuestionAnswerAdapterViewHolder(View v){
super(v);
textQuestion = (TextView)v.findViewById(R.id.textQuestion);
bookmarkButton = (ImageButton)v.findViewById(R.id.bookmarkButton);
textAnswer = (TextView)v.findViewById(R.id.textAnswer);
textQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textAnswer.setVisibility(View.GONE);
}
});
}
}
}
I have 10 Items in the recyclerview. I want to show the textview with id textAnswer when textQuestion is clicked and every thing is working fine till now but when i scroll down i can see that ninth item also has the textAnswer field visible. I can understand that this is happening due to onBindViewHolder Method as recyclerView while recycling its item uses previously visible items which are not visible any more. But i have no clue on how to sort it out. Some one please help
The RecyclerView re-uses the ViewHolders so the trick is to set the expandable area to VISIBLE/GONE inside the onBindViewHolder() method. Hopefully you solved your problem by now but for those who run into similar issues like me, a functional example:
An example of an adapter with expendable cardViews:
public class FooAdapter extends RecyclerView.Adapter<FooAdapter.ViewHolder> {
List<LightGroup> mFoos;
List<Boolean> mExpandedFoos;
public GroupAdapter(List<Foo> Foos) {
mFoos = foos;
mExpandedFoos = new ArrayList<>(mFoos.size());
for(int i = 0; i < mGroups.size(); i++){
mExpandedFoos.add(false);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.foo_row, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(mExpandedFoos.get(position)) {
holder.expandableLayout.setVisibility(View.VISIBLE);
} else {
holder.expandableLayout.setVisibility(View.GONE);
}
Foo foo = mFoos.get(position);
holder.fooName.setText(foo.getName());
//Setup the rest of your row views from your Foo object
}
#Override
public int getItemCount() {
return mFoos == null ? 0 : mFoos.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView fooName;
ViewGroup expandableLayout;
ImageButton expandButton;
public ViewHolder(View itemView) {
super(itemView);
fooName = (TextView) itemView.findViewById(R.id.foo_name_textview);
expandableLayout = (ViewGroup) itemView.findViewById(R.id.expandable_part_layout);
expandButton = (ImageButton) itemView.findViewById(R.id.foo_row_expand_button);
expandButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if(v.getId() == expandButton.getId()){
if(mExpandedFoos.get(position)) {
expandableLayout.setVisibility(View.GONE);
} else {
expandableLayout.setVisibility(View.VISIBLE);
}
mExpandedFoos.set(position, !mExpandedFoos.get(position));
}
}
}
}
With layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="4dp"
app:cardPreventCornerOverlap="false"
android:background="#android:color/background_dark"
android:layout_marginBottom="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/top_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="false"
android:layout_alignParentTop="true">
<TextView
android:id="#+id/foo_name_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="#dimen/activity_horizontal_margin"
android:paddingEnd="#dimen/activity_horizontal_margin"
android:gravity="center"/>
<ImageButton
android:id="#+id/foo_row_expand_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="?android:selectableItemBackground"
android:clickable="true"
android:padding="6dp"
android:rotation="90"
android:src="#drawable/ic_play_light" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/expandable_part_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/top_layout"
android:animateLayoutChanges="true"
android:clickable="false"
android:visibility="gone">
<!-- Your expanded content views go here -->
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>

Categories

Resources