how can i set gravity to right for row recyclerview - android

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

Related

How to remove the last item in recyclerview adapter by a button?

I have a recyclerview and I want to delete the last item on it when I click a button that is not in the recyclerview. I want to delete the item and notify the adapter that the item is deleted so I can enter another item. By the way, the items I enter are by edittext and a button.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.brecyclerview.MainActivity"
android:orientation="vertical">
<EditText
android:id="#+id/edit_ten"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Score"
android:inputType="numberSigned|number" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btn_add"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_add"
android:text="Add"
tools:ignore="OnClick" />
<Button
android:id="#+id/btn_undo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_undo"
android:text="Undo"
tools:ignore="OnClick" />
<Button
android:id="#+id/btn_new"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_new"
android:text="New Game" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleViewContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:itemCount="8" />
</LinearLayout>
list_item.xml:
<?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="wrap_content">
<RelativeLayout
android:id="#+id/singleRow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="#+id/userImg"
android:src="#mipmap/ic_launcher"
android:layout_width="60dp"
android:layout_height="60dp" />
<TextView
android:id="#+id/pNametxt"
android:text="User Name"
android:textSize="20sp"
android:layout_marginTop="6dp"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/userImg"
android:layout_toEndOf="#+id/userImg"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp" />
</RelativeLayout>
<View
android:layout_below="#+id/singleRow"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#f2f2f2" />
</RelativeLayout>
MainActivity.java:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
int total = 0;
Button button;
Button button1;
Button button2;
EditText editText;
TextView personName;
RecyclerView recyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager layoutManager;
List<PersonUtils> personUtilsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.btn_add);
button1 = (Button)findViewById(R.id.btn_undo);
button2 = (Button)findViewById(R.id.btn_new);
editText = (EditText)findViewById(R.id.edit_ten);
personName = (TextView)findViewById(R.id.pNametxt);
recyclerView = (RecyclerView) findViewById(R.id.recycleViewContainer);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
personUtilsList = new ArrayList<>();
mAdapter = new CustomRecyclerAdapter(this, personUtilsList);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v == button2) {
MainActivity.this.finish();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}}});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i<personUtilsList.size(); i++)
{
total = personUtilsList.get(i).getPersonName();
}
total += Integer.parseInt(editText.getText().toString());
personUtilsList.add(new PersonUtils(total));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
editText.setText("");
}});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i<personUtilsList.size(); i++)
{
personUtilsList.remove(i).getPersonName();
personUtilsList.remove(new PersonUtils(total));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}}
});
}}
CustomRecyclerAdapter.java:
import android.content.Context;
import android.preference.PreferenceScreen;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.ViewHolder> {
private Context context;
private List<PersonUtils> personUtils;
public CustomRecyclerAdapter(Context context, List personUtils) {
this.context = context;
this.personUtils = personUtils;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.itemView.setTag(personUtils.get(position));
PersonUtils pu = personUtils.get(position);
holder.pName.setText(String.valueOf(pu.getPersonName()));
}
#Override
public int getItemCount() {
return (personUtils.size()>8)?8:personUtils.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView pName;
final Button deleteButton;
public ViewHolder(final View itemView) {
super(itemView);
pName = (TextView) itemView.findViewById(R.id.pNametxt);
deleteButton = (Button) itemView.findViewById(R.id.btn_undo);
}
}}
PersonUtils.java:
public class PersonUtils {
private Integer personName;
public static void remove(int index) {
}
public Integer getPersonName() {
return personName;
}
public void setPersonName(Integer personName) {
this.personName = personName;
}
public PersonUtils(Integer personName) {
this.personName = personName;
}
}
I expect to delete the last item (integer) in the recyclerview and notify the adapter so I can edit the value when needed.
You can add a method in your adapter to remove last item in the list:
public ViewHolder removeLastItem() {
if (personUtils == null || personUtils.isEmpty()) return;
personUtils.removeAt(personUtils.getSize()-1);
notifyDataSetChanged();
}
When the button is clicked, just call:
adapter.removeLastItem()
Check if you are in the last index, then remove the item and use notifyItemRemoved to notify any registered observers:
if(currentPosition == 0){
listOfItems.removeAt(currentPosition)
notifyItemRemoved(currentPosition)
}

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

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 );
}

Facebook Native in feed ads are overlapping to each other in RecyclerView

I have an app which has Recyclerview and I want to put some facebook Native ads in between list items, like every 5 list items 1 native ad will be shown. everything is working perfectly but main problem is when I scroll down adChoice icon is being doubled and on scrolling up also adChoice icons are getting doubled. It seems that ads are overlapping to the previous one.
SCREENSHOT
Any suggestion will help me a lot. Here is the all source code and the official facebook audience network native ad code sample.
dependency
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.volley:volley:1.1.0'
implementation 'com.facebook.android:audience-network-sdk:4.+'
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_id"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
content_layout.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="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="#+id/textViewHead"
android:text="Heading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"/>
<TextView
android:id="#+id/textViewDesc"
android:text="Description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
ads_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:orientation="vertical">
<LinearLayout
android:id="#+id/adChoicesContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|right"
android:orientation="vertical"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="center_vertical"
android:layout_marginBottom="5dp"
android:layout_marginRight="10dp"
android:orientation="horizontal">
<com.facebook.ads.AdIconView
android:id="#+id/adIconView"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
tools:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvAdTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="#android:color/white"
tools:text="Ad Title"/>
<TextView
android:id="#+id/tvAdBody"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ellipsize="end"
android:gravity="center_vertical"
android:lines="3"
android:textColor="#android:color/darker_gray"
tools:text="This is an ad description."/>
</LinearLayout>
</LinearLayout>
<com.facebook.ads.MediaView
android:id="#+id/mediaView"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
>
<TextView
android:id="#+id/sponsored_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:textColor="#android:color/darker_gray"
android:textSize="10sp"/>
<Button
android:id="#+id/btnCTA"
style="?android:attr/borderlessButtonStyle"
android:layout_width="130dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_gravity="right"
android:layout_marginTop="20dp"
android:background="#android:color/darker_gray"
android:gravity="center"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:text="Install Now"
android:textColor="#android:color/white"
android:textSize="14sp"/>
</RelativeLayout>
</LinearLayout>
ContentModel.java
package com.example.my_demo_app.fb_in-feed_ad;
public class ContentModel {
String head, des;
public ContentModel(String head, String des) {
this.head = head;
this.des = des;
}
public String getHead() {
return head;
}
public String getDes() {
return des;
}
}
MyAdapter.java
package com.example.my_demo_app.fb_in-feed_ad;
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.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.facebook.ads.Ad;
import com.facebook.ads.AdChoicesView;
import com.facebook.ads.AdIconView;
import com.facebook.ads.MediaView;
import com.facebook.ads.NativeAd;
import java.util.ArrayList;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int MENU_ITEM_VIEW_TYPE = 0;
public static final int AD_ITEM_VIEW_TYPE = 1;
private final List<Object> mRecyclerViewItems;
private final Context context;
public MyAdapter(List<Object> recyclerViewItems, Context context) {
this.mRecyclerViewItems = recyclerViewItems;
this.context = context;
}
//--------------------getItemViewType
#Override
public int getItemViewType(int position) {
Object recyclerViewItem = mRecyclerViewItems.get(position);
if (recyclerViewItem instanceof ContentModel) {
return MENU_ITEM_VIEW_TYPE;
} else if (recyclerViewItem instanceof Ad) {
return AD_ITEM_VIEW_TYPE;
} else {
return -1;
}
}
//--------------------getItemCount
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
//--------------------onCreateViewHolder
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
if (viewType==MENU_ITEM_VIEW_TYPE){
View menuItemView = inflater.inflate(R.layout.content_layout, parent, false);
return new MenuItemHolder(menuItemView);
}else if (viewType==AD_ITEM_VIEW_TYPE){
View adItemView = inflater.inflate(R.layout.ads_layout, parent, false);
return new AdHolder(adItemView);
}
return null;
}
//--------------------onBindViewHolder
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int itemType = getItemViewType(position);
if (itemType==MENU_ITEM_VIEW_TYPE){
MenuItemHolder menuItemHolder = (MenuItemHolder) holder;
ContentModel contentModel = (ContentModel) mRecyclerViewItems.get(position);
menuItemHolder.txtH.setText(contentModel.getHead());
menuItemHolder.txtD.setText(contentModel.getDes());
}else if (itemType==AD_ITEM_VIEW_TYPE){
AdHolder nativeAdViewHolder = (AdHolder) holder;
NativeAd nativeAd = (NativeAd) mRecyclerViewItems.get(position);
AdIconView adIconView = nativeAdViewHolder.adIconView;
TextView tvAdTitle = nativeAdViewHolder.tvAdTitle;
TextView tvAdBody = nativeAdViewHolder.tvAdBody;
Button btnCTA = nativeAdViewHolder.btnCTA;
LinearLayout adChoicesContainer = nativeAdViewHolder.adChoicesContainer;
MediaView mediaView = nativeAdViewHolder.mediaView;
TextView sponsorLabel = nativeAdViewHolder.sponsorLabel;
tvAdTitle.setText(nativeAd.getAdvertiserName());
tvAdBody.setText(nativeAd.getAdBodyText());
btnCTA.setText(nativeAd.getAdCallToAction());
sponsorLabel.setText(nativeAd.getSponsoredTranslation());
AdChoicesView adChoicesView = new AdChoicesView(context, nativeAd, true);
adChoicesContainer.addView(adChoicesView);
List<View> clickableViews = new ArrayList<>();
clickableViews.add(btnCTA);
clickableViews.add(mediaView);
nativeAd.registerViewForInteraction(nativeAdViewHolder.container, mediaView, adIconView, clickableViews);
}
}
//--------------------MenuItemHolder
public class MenuItemHolder extends RecyclerView.ViewHolder{
public TextView txtH, txtD;
public MenuItemHolder(View itemView) {
super(itemView);
txtH = (TextView) itemView.findViewById(R.id.textViewHead);
txtD = (TextView) itemView.findViewById(R.id.textViewDesc);
}
}
//--------------------AdHolder
public class AdHolder extends RecyclerView.ViewHolder{
AdIconView adIconView;
TextView tvAdTitle;
TextView tvAdBody;
Button btnCTA;
View container;
TextView sponsorLabel;
LinearLayout adChoicesContainer;
MediaView mediaView;
AdHolder(View itemView) {
super(itemView);
this.container = itemView;
adIconView = (AdIconView) itemView.findViewById(R.id.adIconView);
tvAdTitle = (TextView) itemView.findViewById(R.id.tvAdTitle);
tvAdBody = (TextView) itemView.findViewById(R.id.tvAdBody);
btnCTA = (Button) itemView.findViewById(R.id.btnCTA);
adChoicesContainer = (LinearLayout) itemView.findViewById(R.id.adChoicesContainer);
mediaView = (MediaView) itemView.findViewById(R.id.mediaView);
sponsorLabel = (TextView) itemView.findViewById(R.id.sponsored_label);
}
}
}
MainActivity.java
package com.example.my_demo_app.fb_in-feed_ad;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.NativeAd;
import com.facebook.ads.NativeAdListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String URL_DATA = "https://res.cloudinary.com/ravi40/raw/upload/v1532239134/my_json/heroes_list.json";
private RecyclerView recyclerView;
private List<Object> mRecyclerViewItems;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerViewItems = new ArrayList<>();
//--------------------Native Ad
NativeAd nativeAd = new NativeAd(getApplicationContext(), "IMG_16_9_LINK#YOUR_FACEBOOK_NATIVE_AD_PLACEMENT_ID_WILL_GOES_HERE"); // IMG_16_9_LINK# denote only testing purpose
nativeAd.setAdListener(new NativeAdListener() {
#Override
public void onMediaDownloaded(Ad ad) {
}
#Override
public void onError(Ad ad, AdError adError) {
}
#Override
public void onAdLoaded(Ad ad) {
for (int i=4; i<mRecyclerViewItems.size()+4; i+=5)
mRecyclerViewItems.add(i, ad);
adapter.notifyDataSetChanged();
}
#Override
public void onAdClicked(Ad ad) {
}
#Override
public void onLoggingImpression(Ad ad) {
}
});
nativeAd.loadAd();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("heroes");
for (int i = 0; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
ContentModel item = new ContentModel(
o.getString("name"),
o.getString("about")
);
mRecyclerViewItems.add(item);
}
adapter = new MyAdapter(mRecyclerViewItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Ad are getting overlapped when adding in the container. The solution is to clear the container before adding the ads again.
For example:
AdChoicesView adChoicesView = new AdChoicesView(context, nativeAd, true);
// Clear the container.
adChoicesContainer.removeAllViews()
adChoicesContainer.addView(adChoicesView);

RecyclerView OnClicklistener is unresponsive

Firstly I know there are hundreds of these questions but the answers have not solved my problem. I suspect it's something small I'm missing, basically I've added a RecyclerView and need to start a new activity when a card is clicked.
I've been following this tutorial and it's been smooth sailing up until this point.
https://guides.codepath.com/android/using-the-recyclerview
This is the Recycler
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bgImg"
android:scaleType="centerCrop"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/RV"
/>
</FrameLayout>
This is the card
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp"
android:clickable="true"
android:background="?android:attr/selectableItemBackground">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/vendor_image2"
android:layout_width="fill_parent"
android:layout_height="240dp"
android:padding="5dp" />
<RelativeLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/vendor_image2"
>
<TextView
android:id="#+id/vendor_name2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:paddingBottom="5dp"/>
<TextView
android:id="#+id/vendor_content2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="7dp"
android:layout_toEndOf="#+id/vendor_name2"
android:textColor="#color/text_col"
android:paddingBottom="5dp" />
<TextView
android:id="#+id/vendor_suburb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="italic"
android:textColor="#color/text_col"
android:layout_below="#+id/vendor_name2"
android:layout_marginLeft="10dp" />
<RatingBar
android:id="#+id/MyRating2"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/vendor_suburb2"
android:layout_marginLeft="10dp"
android:isIndicator="true"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:numStars="5"
android:textColor="#android:color/black"
android:rating="3.5"
android:stepSize="0.1" />
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
And finally the Adapter and Handler
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
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.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.iconiccode.android.guestloc8tor.SQL.DatabaseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class VendorRecycleAdapter extends RecyclerView.Adapter<VendorRecycleAdapter.VendorHolder>
{
public List<Vendor> vendorList;
private DatabaseHandler dbHandler = new DatabaseHandler(MyApp.getContext());
private Vendor currentVendor;
int cate;
Activity thiscontext;
public VendorRecycleAdapter(Activity context, int Cate)
{
this.cate=Cate;
this.thiscontext=context;
}
#Override
public VendorHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(thiscontext);
//View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);
View view = inflater.inflate(R.layout.vendor_list_cards,parent,false);
return new VendorHolder(view);
}
#Override
public void onBindViewHolder(VendorHolder holder, int position)
{
vendorList = dbHandler.getVendorData(cate);
currentVendor = vendorList.get(position);
// Get the image string from the Vendor object
String vendorImage = currentVendor.getImage();
Log.e("Vendor Adapter Image", vendorImage);
// Get the name string from the Vendor object
String vendorName = currentVendor.getCompanyName();
Log.e("Vendor Adapter Name", vendorName);
// Get the content string from the Vendor object
String vendorContent = currentVendor.getContent();
// Get the location string from the Vendor object
String vendorSuburb = currentVendor.getSuburb();
Log.e("Vendor Adapter Suburb", vendorSuburb);
// Find the TextView with view ID vendor_name
// Display the name of the current vendor in that TextView
holder.Vvendor_name.setText(vendorName);
holder.Vvendor_image.setImageResource(R.drawable.loading);
ImageLoader imageLoader;
DisplayImageOptions options;
imageLoader = ImageLoader.getInstance();
String url = vendorImage;
imageLoader.init(ImageLoaderConfiguration.createDefault(MyApp.getContext()));
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.loading)
.showImageOnFail(R.drawable.b4f29385)
.resetViewBeforeLoading(true).cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300)).build();
imageLoader.displayImage(url, holder.Vvendor_image);
// Find the TextView with view ID vendor_content
holder.Vvendor_content.setText(vendorContent);
holder.Vvendor_suburb.setText(vendorSuburb);
}
#Override
public int getItemCount()
{
vendorList = dbHandler.getVendorData(cate);
return vendorList.size();
}
public class VendorHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public ImageView Vvendor_image;
public TextView Vvendor_name,Vvendor_content,Vvendor_suburb;
public RatingBar Vrating;
public VendorHolder(View itemView)
{
//These pull as null
super(itemView);
Vvendor_image = (ImageView)itemView.findViewById(R.id.vendor_image2);
Vvendor_name = (TextView)itemView.findViewById(R.id.vendor_name2);
Vvendor_content =(TextView)itemView.findViewById(R.id.vendor_content2);
Vvendor_suburb = (TextView)itemView.findViewById(R.id.vendor_suburb2);
Vrating = (RatingBar) itemView.findViewById(R.id.MyRating2);
}
#Override
public void onClick(View v)
{
// int position = getAdapterPosition();
// currentVendor = vendorList.get(position);
Intent intent = new Intent(thiscontext,VendorDetailsActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
String Category = Integer.toString(cate);
JSONObject message = currentVendor.getAllData();
try {
intent.putExtra("IMAGE", message.getString("IMAGE"));
intent.putExtra("URL", message.getString("URL"));
intent.putExtra("CONTENT", message.getString("CONTENT"));
intent.putExtra("COMPANY_NAME", message.getString("COMPANY_NAME"));
intent.putExtra("TEL", message.getString("TEL"));
intent.putExtra("BOOKING_URL", message.getString("BOOKING_URL"));
intent.putExtra("LAT", message.getString("LAT"));
intent.putExtra("LON", message.getString("LON"));
intent.putExtra("STREET", message.getString("STREET"));
intent.putExtra("SUBURB", message.getString("SUBURB"));
intent.putExtra("PROVINCE", message.getString("PROVINCE"));
intent.putExtra("CITY", message.getString("CITY"));
intent.putExtra("CAT",Category);
} catch (JSONException json)
{
Log.e("ERROR", json.getMessage());
}
thiscontext.startActivity(intent);
}
}
}
Any help would be greatly appreciated.
Thanks
I think you just forgot to set the onClickListener in your ViewHolder constructor:
public VendorHolder(View itemView)
{
//These pull as null
super(itemView);
Vvendor_image = (ImageView)itemView.findViewById(R.id.vendor_image2);
Vvendor_name = (TextView)itemView.findViewById(R.id.vendor_name2);
Vvendor_content =(TextView)itemView.findViewById(R.id.vendor_content2);
Vvendor_suburb = (TextView)itemView.findViewById(R.id.vendor_suburb2);
Vrating = (RatingBar) itemView.findViewById(R.id.MyRating2);
// If it should be triggered only when clicking on a specific view, replace itemView with the view you want.
itemView.setOnClickListener(this);
}

CheckBox in recyclerview not working and unable to pass the checked items to another fragment

I have a favorite checkbox in my recyclerview. My problem is checkbox is not clickable inside recyclerview. and i have to pass the ticked recyclerview items to another recyclerview. Really I got stucked here . anyone please help me. Thanks in advance.
recycler_view_item.xml
<?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="210dp"
android:background="#color/cardview_light_background"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="210dp">
<View
android:id="#+id/divider"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#color/common_action_bar_splitter" />
<ImageView
android:id="#+id/PROJECT_image"
android:layout_width="match_parent"
android:layout_height="#dimen/list_item_avatar_size"
android:layout_below="#id/divider"
android:background="#drawable/mirlogo"
android:scaleType="fitXY" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" STATUS "
android:background="#color/common_action_bar_splitter"
android:id="#+id/PROJECT_status"
android:rotation="-45"
android:layout_below="#+id/divider"
android:layout_alignLeft="#+id/divider"
android:layout_alignStart="#+id/divider"
android:layout_marginTop="15dp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#80000000"
android:layout_alignParentBottom="true">
<TextView
android:id="#+id/PROJECT_name"
android:textColor="#color/cardview_light_background"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Project"
android:textSize="18sp"
android:textAppearance="?attr/textAppearanceListItem" />
<TextView
android:id="#+id/PROJECT_city"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/PROJECT_name"
android:text="kerala"
android:textColor="#color/common_action_bar_splitter"
android:textSize="16sp"
android:textAppearance="?attr/textAppearanceListItem" />
<TextView
android:id="#+id/PROJECT_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/PROJECT_city"
android:text="india"
android:background="#android:color/holo_green_dark"
android:textColor="#color/cardview_light_background"
android:textSize="15sp"
android:textAppearance="?attr/textAppearanceListItem" />
<CheckBox
android:id="#+id/PROJECT_fav"
android:layout_width="30sp"
android:layout_height="30sp"
android:layout_alignBottom="#+id/PROJECT_city"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:background="#drawable/selector"
android:button="#null"
/>
</RelativeLayout>
</RelativeLayout>
RecyclerviewAdapter
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.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.root5solutions.mirrealtors.R;
public class HomeDataManager extends RecyclerView.Adapter<HomeDataManager.RecyclerViewHolder> {
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView mProjectName, mProjectCity, mProjectType, mProjectStatus;
ImageView mImage;
CheckBox mCheck;
RecyclerViewHolder(View itemView) {
super(itemView);
mProjectName = (TextView) itemView.findViewById(R.id.PROJECT_name);
mProjectCity = (TextView) itemView.findViewById(R.id.PROJECT_city);
mProjectType = (TextView) itemView.findViewById(R.id.PROJECT_type);
mProjectStatus = (TextView) itemView.findViewById(R.id.PROJECT_status);
mImage = (ImageView) itemView.findViewById(R.id.PROJECT_image);
mCheck = (CheckBox) itemView.findViewById(R.id.PROJECT_fav);
}
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerview_item, viewGroup, false);
return new RecyclerViewHolder(v);
}
#Override
public void onBindViewHolder(final RecyclerViewHolder viewHolder, int i) {
// get the single element from the main array
final HomeProjects projects = HomeProjects.PROJECTS[i];
// Set the values
viewHolder.mProjectName.setText(projects.get(HomeProjects.Field.NAME));
viewHolder.mProjectCity.setText(projects.get(HomeProjects.Field.CITY));
viewHolder.mProjectType.setText(projects.get(HomeProjects.Field.TYPE));
viewHolder.mProjectStatus.setText(projects.get(HomeProjects.Field.STATUS));
viewHolder.mImage.setImageResource(projects.geti(HomeProjects.Field.IMAGE));
viewHolder.mCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
viewHolder.mCheck.setChecked(!viewHolder.mCheck.isChecked());
Log.d("Tag Name", "Log Message");
}
});
#Override
public int getItemCount() {
return HomeProjects.PROJECTS.length;
}
}
RecyclerviewFragment
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.root5solutions.mirrealtors.HomeRecyclerDetailActivity;
import com.example.root5solutions.mirrealtors.ProjectRecyclerDetailActivity;
import com.example.root5solutions.mirrealtors.R;
import com.example.root5solutions.mirrealtors.projectdatabase.HomeDataManager;
import com.example.root5solutions.mirrealtors.projectdatabase.HomeProjects;
import com.example.root5solutions.mirrealtors.projectdatabase.Projects;
import com.example.root5solutions.mirrealtors.projectdatabase.RecyclerClickListener;
import com.kogitune.activity_transition.ActivityTransitionLauncher;
public class RecyclerTab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_tab1_recycler, container, false);
RecyclerView rv = (RecyclerView) v.findViewById(R.id.home_recyclerview);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
rv.setLayoutManager(llm);
rv.setHasFixedSize(true); // to improve performance
rv.setAdapter(new HomeDataManager()); // the projectdatabase manager is assigner to the RV
rv.addOnItemTouchListener( // and the click is handled
new RecyclerClickListener(getContext(), new RecyclerClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(getActivity(), HomeRecyclerDetailActivity.class);
intent.putExtra(HomeRecyclerDetailActivity.ID, HomeProjects.PROJECTS[position].getId());
ActivityTransitionLauncher.with(getActivity()).from(view).launch(intent);
}
}));
return v;
}
}
Remove the onClickListener and set onCheckedChangeListener. Then save your list to an array in Sharedpreference
viewHolder.mCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item Favorited", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item Unfavorited", Snackbar.LENGTH_SHORT);
snackbar.show();
}
int position = viewHolder.getAdapterPosition();
mCheckedItems.put(position, isChecked);
List<Integer> selected = new ArrayList<>();
for (int i = 0; i < mCheckedItems.size(); i++) {
final boolean checked = mCheckedItems.valueAt(i);
if (checked) {
selected.add(mCheckedItems.keyAt(i));
}
}
Log.e("Checked Array = ", String.valueOf(selected));
SharedPreferences prefs = v1.getContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("Checkbox", String.valueOf(selected));
edit.commit();
Log.e("Shared Preference = ", String.valueOf(edit));
}
});

Categories

Resources