How to get two different imageview in Recyclerview row - android

how do i get two different imageview and textviews in each row of recyclerview
and i want to make each imageview clickable .... i have done this in list view but don't know how to do it in recycler view .... so help me to acheive this ... thanks in advance
here is my layout file recyclerview row
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="2">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="250dp"
android:layout_weight="1"
android:orientation="horizontal"
android:weightSum="2">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="6dp"
android:scaleType="fitXY" />
/>
<TextView
android:id="#+id/category_title_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/thumbnail"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:ellipsize="end"
android:maxLines="1"
android:text="Title"
android:textColor="#android:color/black"
android:textSize="10dp" />
<TextView
android:id="#+id/tv_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/category_title_one"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:ellipsize="end"
android:maxLines="1"
android:text="Price"
android:textColor="#android:color/black"
android:textSize="10dp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/thumbnail2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="6dp"
android:scaleType="fitXY" />
/>
<TextView
android:id="#+id/category_title_two"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/thumbnail2"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:ellipsize="end"
android:maxLines="1"
android:text="Title"
android:textColor="#android:color/black"
android:textSize="10dp">
</TextView>
<TextView
android:id="#+id/tv_price2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/category_title_two"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:ellipsize="end"
android:maxLines="1"
android:text="Price"
android:textColor="#android:color/black"
android:textSize="10dp">
</TextView>
</RelativeLayout>
</LinearLayout>
here is my adapterclass
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ViewHolder> {
private Context context;
public ImageLoader mImageLoader;
//List of superHeroes
List<ListOfData> superHeroes;
public RecyclerViewDataAdapter(List<ListOfData> superHeroes, Context context) {
super();
//Getting all the superheroes
this.superHeroes = superHeroes;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerview_row, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListOfData superHero = superHeroes.get(position);
mImageLoader = MyApplication.getInstance().getImageLoader();
mImageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView1, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
mImageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView2, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.imageView1.setImageUrl(superHero.getImageUrl(), mImageLoader);
holder.imageView2.setImageUrl(superHero.getImageUrl(), mImageLoader);
holder.textViewName1.setText(superHero.getName());
holder.textViewName2.setText(superHero.getName());
//holder.textViewRank.setText(String.valueOf(superHero.getRank()));
//holder.textViewRealName.setText(superHero.getRealName());
//holder.textViewCreatedBy.setText(superHero.getCreatedBy());
//holder.textViewFirstAppearance.setText(superHero.getFirstAppearance());
String powers = "";
/* for(int i = 0; i<superHero.getPowers().size(); i++){
powers+= superHero.getPowers().get(i);
}*/
//holder.textViewPowers.setText(powers);
}
#Override
public int getItemCount() {
return superHeroes.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public NetworkImageView imageView1;
public NetworkImageView imageView2;
public TextView textViewName1;
public TextView textViewName2;
public TextView textViewRank;
public TextView textViewRealName;
public TextView textViewCreatedBy;
public TextView textViewFirstAppearance;
public TextView textViewPowers;
public ViewHolder(View itemView) {
super(itemView);
imageView1 = (NetworkImageView) itemView.findViewById(R.id.thumbnail);
imageView2 = (NetworkImageView) itemView.findViewById(R.id.thumbnail2);
textViewName1 = (TextView) itemView.findViewById(R.id.category_title_one);
textViewName2 = (TextView) itemView.findViewById(R.id.category_title_two);
/* textViewRank= (TextView) itemView.findViewById(R.id.textViewRank);
textViewRealName= (TextView) itemView.findViewById(R.id.textViewRealName);
textViewCreatedBy= (TextView) itemView.findViewById(R.id.textViewCreatedBy);
textViewFirstAppearance= (TextView) itemView.findViewById(R.id.textViewFirstAppearance);
textViewPowers= (TextView) itemView.findViewById(R.id.textViewPowers);
*/
}
}
}
here is Json part
public class Pants extends Fragment {
//Creating a List of superheroes
public Context context;
public List<ListOfData> listSuperHeroes;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public Pants() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.tshirts_pants_shirts, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
//Calling method to get data
getData();
return view;
}
private void getData() {
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(getActivity(), "Loading Data", "Please wait...", false, false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ProductConfig.DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array) {
listSuperHeroes = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
ListOfData superHero = new ListOfData();
JSONObject json = null;
try {
json = array.getJSONObject(i);
superHero.setImageUrl(json.getString(ProductConfig.TAG_IMAGE_URL));
superHero.setName(json.getString(ProductConfig.TAG_NAME));
/*superHero.setRank(json.getInt(ProductConfig.TAG_RANK));
superHero.setRealName(json.getString(ProductConfig.TAG_REAL_NAME));
superHero.setCreatedBy(json.getString(ProductConfig.TAG_CREATED_BY));
superHero.setFirstAppearance(json.getString(ProductConfig.TAG_FIRST_APPEARANCE));
*/
ArrayList<String> powers = new ArrayList<String>();
JSONArray jsonArray = json.getJSONArray(ProductConfig.TAG_POWERS);
for (int j = 0; j < jsonArray.length(); j++) {
powers.add(((String) jsonArray.get(j)) + "\n");
}
superHero.setPowers(powers);
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(superHero);
}
adapter = new RecyclerViewDataAdapter(listSuperHeroes, context);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
//Initializing our superheroes list
}
}

Do the images of the same row belong to the same hero or are they from different heroes?
If they are from different heroes:
1) Change your recyclerview row layout to have only 1 imageview and 2 textviews (remove the second relativelayout)
2) Change the LayoutManager of your recyclerview to GridLayoutManager with 2 columns:
GridLayoutManager glm = new GridLayoutManager(getContext(), 2);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return 2;
}
});
recyclerView.setLayoutManager(glm);
3) Change your onBindViewHolder meethod and ViewHolder class accordingly (remove the second imageview and the third and fourth textviews)
4) Make the image clickable adding the following to the onBindViewHolder method:
holder.imageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});

If I understand your issue correctly, in onBindViewHolder you're setting both of your TextViews and ImageViews using the same data. Which is why you're getting the same image twice. What you should do is pass Map<int, List<Object>> superHeroes into your RecyclerView. The key would be the row item number and the list would contain objects for both your superheroes with a title and image uri.
To make your individual ImageViewsclickable, set anonClickListeneron eachonBindViewHolder` and handle their respect logic.

From this code I can see that you set the same image to imageView1 and imageView2 and the same text for textViewName1 and textViewName2
holder.imageView1.setImageUrl(superHero.getImageUrl(), mImageLoader);
holder.imageView2.setImageUrl(superHero.getImageUrl(), mImageLoader);
holder.textViewName1.setText(superHero.getName());
holder.textViewName2.setText(superHero.getName());
If you would like to have two different images, you have to set two different images and not the same one.
For the click handling you have to set the onClickListener on the image/text/button/view that you want making clickable, for example if you want that your imageView1 is clickable you have to do
holder.imageView1.setOnClickListener(this);
than you have to implements the interface
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ViewHolder> implements View.OnClickListener {
and after that you can handle the onClick event in the overrided method
#Override
public void onClick(View v) {
}
I hope that helps.

Even though the question is 4 years old. I going to post an answer so other people can see it.
Since you are providing an array, the position is getting the values ( image and text) item from each index of the array.
What you need to do is provide the array as you did but make sure each index of the array contain image1, text1, image2 and text2.

Related

multiple recyclerviews?

I want to make my homepage with two row with recyclerview
with data of books and the events which are display independent of each other how can i accomplish it I want to add event to the my code how can i do it?
MoviesAdapter.java
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {
private List<Movie> moviesList;
public Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
thumbnail = (ImageView) view.findViewById(R.id.book);
}
}//End of MyViewHolder class
public MoviesAdapter(List<Movie> moviesList) {
this.moviesList = moviesList;
}
//display different items in the data set
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.movie_list_row, parent, false);
return new MyViewHolder(itemView);
}
//display data at specified location
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.title.setText(moviesList.get(position).getTitle());
holder.thumbnail.setImageResource(moviesList.get(position).getImage());
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
I want to make my page like this
It should be fine to use a LinearLayout with 3 RecyclerViews in it and create an Adapter for each of them. Nested RecyclerViews would only make sense if you had a lot of categories.
I done it with the three recyclerview and their adapter class here is the code of only MainActivity.java and activity.xml
MainActivity.java
public class MainActivity extends AppCompatActivity {
private List<Book> bookList = new ArrayList<>();
private List<Author> authorList = new ArrayList<>();
private List<Event> eventList = new ArrayList<>();
private RecyclerView recyclerView1;
private RecyclerView recyclerView2;
private RecyclerView recyclerView3;
private BookAdapter bAdapter;
private AuthorAdapter aAdapter;
private EventAdapter eAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView1 = findViewById(R.id.recycler_book);
bAdapter = new BookAdapter(this,bookList);
recyclerView1.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView1.setLayoutManager(mLayoutManager);
recyclerView1.setAdapter(bAdapter);
prepareBookData();
//second recycler
recyclerView2 = findViewById(R.id.recycler_author);
aAdapter = new AuthorAdapter(this,authorList);
recyclerView2.setHasFixedSize(true);
RecyclerView.LayoutManager aLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView2.setLayoutManager(aLayoutManager);
recyclerView2.setAdapter(aAdapter);
prepareAuthorData();
//third recycler
recyclerView3 = (RecyclerView) findViewById(R.id.recycler_event);
eAdapter = new EventAdapter(this,eventList);
recyclerView3.setHasFixedSize(true);
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
// RecyclerView.LayoutManager eLayoutManager = new GridLayoutManager(this,1,GridLayoutManager.HORIZONTAL,false);
recyclerView3.setLayoutManager(eLayoutManager);
recyclerView3.setAdapter(eAdapter);
prepareEventData();
}
private void prepareBookData(){
int[] drawableArray = {R.drawable.youcanwin, R.drawable.halfgirl};
String[] nameArray = {"You Can Win", "Half Girlfriend"};
Book a=new Book(nameArray[0],drawableArray[0]);
bookList.add(a);
Book b=new Book(nameArray[1],drawableArray[1]);
bookList.add(b);
Book c=new Book(nameArray[0],drawableArray[0]);
bookList.add(c);
bAdapter.notifyDataSetChanged();
}
private void prepareAuthorData(){
int[] drawableArray = {R.drawable.youcanwin, R.drawable.halfgirl};
String[] nameArray = {"You Can Win", "Half Girlfriend"};
Author a=new Author(nameArray[0],drawableArray[0]);
authorList.add(a);
Author b=new Author(nameArray[1],drawableArray[1]);
authorList.add(b);
Author c=new Author(nameArray[0],drawableArray[0]);
authorList.add(c);
Author d=new Author(nameArray[1],drawableArray[1]);
authorList.add(d);
bAdapter.notifyDataSetChanged();
}
private void prepareEventData(){
String[] desArray = {"new","old"};
String[] nameArray = {"You Can Win", "Half Girlfriend"};
Event a=new Event(nameArray[0],desArray[0]);
eventList.add(a);
Event b=new Event(nameArray[0],desArray[0]);
eventList.add(b);
Event c=new Event(nameArray[0],desArray[0]);
eventList.add(c);
bAdapter.notifyDataSetChanged();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
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="fill_parent"
android:layout_height="wrap_content"
tools:context="com.example.hardik.threerecycler.MainActivity"
android:background="#e6edec">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
app:cardCornerRadius="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Books"
android:textSize="20sp"
android:textStyle="bold" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_book"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_marginTop="20dp" />
</android.support.v7.widget.CardView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Authors"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginTop="10dp"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_author"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_below="#+id/recycler_book"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Events"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginTop="10dp"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_event"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_below="#+id/recycler_author"
android:layout_marginTop="5dp"/>
</LinearLayout>

Trying to set a click listener to a recyclerView

I'm new to Android programming and trying to set a click listener to open another activity. The list loads fine, but when I click the items, nothing happens. This is my adapter:
public interface OnItemClickListener {
void onItemClick(Product product);
}
private List<Product> productList;
private double currentLatitude, currentLongitude;
private Context context;
private final OnItemClickListener listener;
public AdapterForProducts(List<Product> productList, OnItemClickListener listener, double currentLatitude, double longitude, Context context){
this.currentLatitude = currentLatitude;
this.currentLongitude = longitude;
this.productList = productList;
this.context = context;
this.listener = listener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
ViewHolderForProducts holder = new ViewHolderForProducts(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
//Use the provided View Holder on the onCreateViewHolder method to populate the current row on the RecyclerView
ViewHolderForProducts holder = (ViewHolderForProducts) viewHolder;
Product product = productList.get(position);
String distanceText = "Distancia: " + round(distance(product.getLatitude(), product.getLongitude())) + " meters";
holder.bind(productList.get(position), listener, distanceText);
}
#Override
public int getItemCount() {
return productList.size();
}
the viewHolder:
public ViewHolderForProducts(View view){
super(view);
cardView = (CardView) itemView.findViewById(R.id.cardView);
name = (TextView) view.findViewById(R.id.product_name);
value = (TextView) view.findViewById(R.id.product_value);
distance = (TextView) view.findViewById(R.id.product_distance);
}
public void bind(final Product product, final AdapterForProducts.OnItemClickListener listener,
String distanceText) {
name.setText(product.getName());
value.setText("Preço: " + product.getValue());
distance.setText(distanceText);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(product);
}
});
}
And I'm calling it in the activity like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_and_show_product_list);
Bundle extras = getIntent().getExtras();
if (extras != null) {
latitude = extras.getDouble("latitude");
longitude = extras.getDouble("longitude");
}
query = "";
query_field = (EditText) findViewById(R.id.query_field);
searchButton = (Button) findViewById(R.id.searchProductButton);
requestQueue = Volley.newRequestQueue(getApplicationContext());
recyclerView = (RecyclerView) findViewById(R.id.recycler);
productList = new ArrayList<>();
fillProductListByName();
adapterForProducts = new AdapterForProducts(productList, new AdapterForProducts.OnItemClickListener() {
#Override
public void onItemClick(Product product) {
showProductOnMap(product);
}
}, latitude, longitude, getApplication());
recyclerView.setAdapter(adapterForProducts);
adapterForProducts.notifyDataSetChanged();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query = query_field.getText().toString();
productList.clear();
fillProductListByName();
adapterForProducts.notifyDataSetChanged();
}
});
}
This is the list item xml:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/activity_vertical_margin"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="#dimen/activity_vertical_margin"
app:cardElevation="#dimen/activity_vertical_margin">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:clickable="true"
android:padding="16dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp" />
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_toRightOf="#+id/imageView"
android:text="Product Name"
android:textSize="14sp" />
<TextView
android:id="#+id/product_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginStart="15dp"
android:layout_toRightOf="#+id/product_name"
android:text="Price: " />
<TextView
android:id="#+id/product_distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="51dp"
android:layout_marginStart="51dp"
android:layout_toEndOf="#+id/product_value"
android:layout_toRightOf="#+id/product_value"
android:text="Distance:" />
</RelativeLayout>
I got it working. Apparently, this implementation doesn't work if there is some other clickable object inside the list item, as was the case with:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:clickable="true"
android:padding="16dp">
All I did was to erase the android:clickable="true" from the RelativeLayout
When you set the attr android:clickable="true" to the parent layout, its click method
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(product);
}
});
will only be called if its childs doesn't have the clickable = true or have a OnClickListener set.
Actually, you don't need all these android:clickable="true".
When you set android:clickable="true" you are setting a empty ClickListener to this view.
The click event is passed to the lowest view in the layout hierarchy with a ClickListener implemented, even with empty body. This is the cause of your bug, and its because of this that you have to remove the android:clickable="true".
Removing the android:clickable="true", removes the empty ClickListener, and now the lowest view in the layout hierarchy is the CardView with this ClickListener:
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(product);
}
});
So, this is the ClickListener that will be called.

RecyclerView is not showing on UI

I am getting data from TMDB API and displaying it on screen.
Right now, I am trying to get reviews from that API.
Everything seems fine, I created: adapter,model,interface,xml and activities, but it is not displaying any data.
API is working fine, I can see from Android Monitor that I am getting right data.
Somebody help, please.
Bellow is my DetailsActivity where I am trying to fetch data:
public class MovieDetailActivity extends AppCompatActivity {
public static final String EXTRA_MOVIE = "EXTRA_MOVIE";
private Movie mMovie;
private Reviews mReviews;
private Genres mGenres;
public ReviewAdapter rAdapter;
ImageView backdrop;
ImageView poster;
TextView title;
TextView description;
TextView releaseDate;
TextView voteAverage;
RecyclerView reviews;
TextView content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
if (getIntent().hasExtra(EXTRA_MOVIE)) {
mMovie = getIntent().getParcelableExtra(EXTRA_MOVIE);
} else {
throw new IllegalArgumentException("Detail activity must receive a movie parcelable");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
CollapsingToolbarLayout toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
toolbarLayout.setTitle(mMovie.getTitle());
reviews = (RecyclerView) findViewById(R.id.recyclerView2);
reviews.setLayoutManager(new LinearLayoutManager(this));
rAdapter = new ReviewAdapter(MovieDetailActivity.this);
reviews.setAdapter(rAdapter);
getReviews(mMovie.getId());
poster = (ImageView) findViewById(R.id.movie_poster);
String internetUrl = "http://image.tmdb.org/t/p/w500";
Glide.with(this)
.load(mMovie.getPoster())
.into(poster);
Glide.with(this)
.load(mMovie.getBackdrop())
.into(backdrop);
}
private void getReviews(Integer id) {
RestAdapter.getMovieService().getReviews(id, new Callback<ReviewWraper>() {
#Override
public void success(ReviewWraper reviewWraper, Response response) {
rAdapter.setReviewList(reviewWraper.getResults());
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
public static class MovieViewHolder extends RecyclerView.ViewHolder {
public ImageView reviewPicture;
public TextView reviewUsername;
public TextView reviewDate;
public TextView reviewTime;
public TextView reviewComment;
public MovieViewHolder(View itemView) {
super(itemView);
reviewPicture = (ImageView) itemView.findViewById(R.id.picture_review);
reviewUsername = (TextView) itemView.findViewById(R.id.username_review);
reviewDate = (TextView) itemView.findViewById(R.id.date_review);
reviewTime = (TextView) itemView.findViewById(R.id.time_review);
reviewComment = (TextView) itemView.findViewById(R.id.review_comment);
}
}
Here is my adapter class:
public class ReviewAdapter extends RecyclerView.Adapter<MovieDetailActivity.MovieViewHolder> {
private List<Reviews> rReviewList;
private LayoutInflater rInflater;
private Context rContext;
public ReviewAdapter(Context context) {
this.rContext = context;
this.rInflater = LayoutInflater.from(context);
this.rReviewList = new ArrayList<>();
}
public MovieDetailActivity.MovieViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
// create a new view
View view = rInflater.inflate(R.layout.row_review, parent, false);
return new MovieDetailActivity.MovieViewHolder(view);
}
#Override
public void onBindViewHolder(MovieDetailActivity.MovieViewHolder holder, int position) {
Reviews reviews = rReviewList.get(position);
Picasso.with(rContext)
.load(reviews.getUrl())
.into(holder.reviewPicture);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Perform click
}
});
}
#Override
public int getItemCount() {
return rReviewList.size();
}
//To update data
public void setReviewList(List<Reviews> reviewsList) {
this.rReviewList = new ArrayList<>();
this.rReviewList.addAll(reviewsList);
notifyDataSetChanged();
}
Bellow is XML 1:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/picture_review"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:adjustViewBounds="true"
android:id="#+id/username_review"
android:layout_width="40dp"
android:layout_height="20dp"
android:width="20dp"
android:height="20dp"
android:textColor="#ffffff" />
<TextView
android:id="#+id/date_review"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textColor="#ffffff" />
<TextView
android:id="#+id/time_review"
android:layout_width="10dp"
android:layout_height="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#ffffff" />
<TextView
android:id="#+id/review_comment"
android:layout_width="250dp"
android:layout_height="250dp"
android:textColor="#ffffff"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/picture_review"
android:layout_toEndOf="#+id/picture_review" />
</RelativeLayout>
And XML 2 with RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.demo.mtin.mtin.MovieDetailActivity"
tools:showIn="#layout/activity_movie_detail">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ffffff" />
Try to give fixed height instead of "wrap_content" on your row in root of Xml 1.
tools:showIn="#layout/activity_movie_detail">
If XML 2 needs to show in XML 1, XML1 must have this -
<include layout="#layout/XML2"/>
See this for more details -
android-how-to-use-tools-with-include-layout

Android recyclerview adding duplicate elements on each activity creation

When I launch a new fragment from my navigation drawer, it's meant to take me to a home page with a cardView of matching profiles. It works great the first time and every profile I want to show up is there. However, when I navigate away from the fragment and then click on it again, the elements are duplicated, and each subsequent time I refresh the page the items are duplicated once more. I believe this problem lies somewhere in my RecyclerView adapter not clearing on an activity create, but I have't been able to pinpoint it. Here's my fragment class
public class HomeFragment extends Fragment {
private CustomListAdapter listAdapter;
private static final String profileUrl = "http://10.0.2.2:3000/apip/buyers/profiles";
private static final String TAG = selectBuyerProfile.class.getSimpleName();
private ProgressDialog pDialog;
private ListView listView;
private List<BuyerProfile> buyersProfiles = new ArrayList<BuyerProfile>();
private View root;
//private RVAdapter recyclerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
RecyclerView rv = (RecyclerView) getActivity().findViewById(R.id.rv);
//rv.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
rv.setItemAnimator(new DefaultItemAnimator());
final RVAdapter recyclerAdapter = new RVAdapter(buyersProfiles);
rv.setAdapter(recyclerAdapter);
RequestQueue mRequestQueue;
Cache cache = new DiskBasedCache(getActivity().getCacheDir(), 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
JsonArrayRequest profileRequest = new JsonArrayRequest(profileUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for(int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
BuyerProfile parsedProfile = new BuyerProfile();
parsedProfile.setBuyerProfTitle(obj.getString("title"));
parsedProfile.setDescription(obj.getString("description"));
parsedProfile.setLocations(obj.getString("locations"));
parsedProfile.setAssetTypes(obj.getString("asset_type"));
parsedProfile.setPropertyStatuses(obj.getString("property_status"));
//parsedProfile.setBuyerId("Select");
buyersProfiles.add(parsedProfile);
} catch (Exception e) {
e.printStackTrace();
}
}
recyclerAdapter.notifyDataSetChanged();
// notifying list adapter about data changes
// so that it renders the list view with updated data
//hidePDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(selectBuyerProfile.this,"Error",Toast.LENGTH_LONG).show();
}
});
mRequestQueue.add(profileRequest);
}
}
And here is my RVAdapter class
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
private Activity activity;
private LayoutInflater inflater;
private List<BuyerProfile> profileItems;
private static boolean itemFavorited;
RVAdapter(List<BuyerProfile> profiles) {
this.profileItems = profiles;
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView description;
TextView locations;
TextView id;
TextView investmentRangeMin;
TextView investmentRangeMax;
TextView assetTypes;
TextView propertyStatuses;
ImageView favoriteButton;
CardView cardView;
PersonViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.titleText);
description = (TextView) itemView.findViewById(R.id.descriptionText);
investmentRangeMin = (TextView) itemView.findViewById(R.id.investmentRangeMin);
investmentRangeMax = (TextView) itemView.findViewById(R.id.investmentRangeMax);
locations = (TextView) itemView.findViewById(R.id.locations);
id = (TextView) itemView.findViewById(R.id.profileNumber);
assetTypes = (TextView) itemView.findViewById(R.id.assetTypes);
propertyStatuses = (TextView) itemView.findViewById(R.id.propertyStatuses);
favoriteButton = (ImageView) itemView.findViewById(R.id.favorite_select);
cardView = (CardView) itemView.findViewById(R.id.cv);
//User selects favorite on a matched profile
itemFavorited = false;
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!itemFavorited) {
favoriteButton.setImageResource(R.drawable.ic_favorite);
//cardView.setCardBackgroundColor(R.color.colorPrimary);
itemFavorited = true;
} else {
favoriteButton.setImageResource(R.drawable.ic_favorite_border);
itemFavorited = false;
}
}
});
}
}
#Override
public int getItemCount() {
return profileItems.size();
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
personViewHolder.name.setText(profileItems.get(i).getBuyerProfTitle());
personViewHolder.description.setText(profileItems.get(i).getDescription());
personViewHolder.locations.setText(profileItems.get(i).getLocations());
personViewHolder.assetTypes.setText(profileItems.get(i).getAssetTypes());
personViewHolder.propertyStatuses.setText(profileItems.get(i).getPropertyStatuses());
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
/*
#Override
public Object getItem(int location) {
return profileItems.get(location);
}
*/
#Override
public long getItemId(int position) {
return position;
}
}
Finally here is my fragments 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"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:padding="0dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Matches"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="false"
android:id="#+id/matchesText"
android:textAlignment="center"
android:textSize="20dp"
android:textColor="#color/navigationBarColor"
android:layout_alignParentStart="false"
android:layout_alignParentBottom="false"
android:layout_alignParentLeft="false"
android:layout_alignParentRight="true"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rv"
android:layout_below="#id/matchesText"
/>
<!-- Thumbnail Image -->
<ImageView
android:id="#+id/imgBillionaire"
android:src="#drawable/ic_perm_identity"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="true"
android:nestedScrollingEnabled="false"
android:visibility="invisible"/>
<!-- Name of Asset -->
<TextView
android:id="#+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imgBillionaire"
android:layout_toRightOf="#+id/imgBillionaire"
android:textSize="#dimen/Title"
android:textStyle="bold" />
<!-- Description -->
<TextView
android:id="#+id/descriptionText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/titleText"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/imgBillionaire"
android:textSize="#dimen/Description" />
<!-- Source -->
<TextView
android:id="#+id/locations"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/descriptionText"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/imgBillionaire"
android:textColor="#color/wealthsource"
android:textSize="#dimen/InvestmentRange" />
<!-- Source -->
<TextView
android:id="#+id/assetTypes"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/locations"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/imgBillionaire"
android:textColor="#color/wealthsource"
android:textSize="#dimen/InvestmentRange" />
<!-- Source -->
<TextView
android:id="#+id/propertyStatuses"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/assetTypes"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/imgBillionaire"
android:textColor="#color/wealthsource"
android:textSize="#dimen/InvestmentRange" />
<!-- Year -->
<TextView
android:id="#+id/profileNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="false"
android:layout_alignParentRight="true"
android:textColor="#color/year"
android:textSize="#dimen/Date" />
</RelativeLayout>
</LinearLayout>
Any ideas why the items in my recyclerview would keep duplicating on each page refresh?
What can possibly be happening is that each time the network request returns, it tries to add every new item to an already existing list inside the fragment.
Depending on how you implement your navigation logic, your fragment won't be destroyed by the system once you navigate away from it, instead calling a series of lifecycle callbacks:
onPause() -> onStop() -> onDestroyView()
And when you return to the fragment, all required lifecycle callbacks will be called until it reaches the active state.
onCreateView() -> onActivityCreated() -> onStart() -> onResume()
More information on fragment's lifecycle works can be found here: https://developer.android.com/guide/components/fragments.html
Since your fragment is not getting destroyed and recreated, your buyersProfiles reference may hold the previous data when you return. Since the network call is not overwriting the original list, it will append the new data fetched from the network next to the existing data each time it calls it's onResponse callback.
This may also affect use cases where you implement some kind of pull-to-refresh logic or refresh button, as the new network call will not clean the list.
One thing you could try to avoid this repetition is adding
buyersProfiles = new ArrayList<BuyerProfile>();
to the top of your onResponse() callback.
Hope it helps.

long Textview flickers when using linkify

I am using linkify to make links clickable in the textview. But whenever text length is big, the text flickers on scrolling or sometimes just disappears. The text view is part of header of recyclerview. Posting relevant code from activity class, its xml and adapter.
The Activity:
public class NewDiscussionDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_discussion_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
aQuery = new AQuery(this);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
ab.setTitle("Discussion");
}
Intent activityIntent = getIntent();
discussion_id = Integer.parseInt(activityIntent.getStringExtra("discussion_id"));
discussion_title = activityIntent.getStringExtra("discussion_title");
discussion_text = activityIntent.getStringExtra("discussion_text");
discussion_image_url = activityIntent.getStringExtra("discussion_image_url");
comment_count = Integer.parseInt(activityIntent.getStringExtra("discussion_comment_no"));
community_id = activityIntent.getStringExtra("community_id");
community_name = activityIntent.getStringExtra("community_name");
is_from_notification = activityIntent.getBooleanExtra("is_notification", false);
// initializing header and footer for List view
footer = getLayoutInflater().inflate(R.layout.main_list_footer, null);
header = getLayoutInflater().inflate(R.layout.discussion_detail_header, null);
prepareHeader(header);
recyclerView = (RecyclerView) findViewById(R.id.comment_list);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(recyclerView.getContext());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mLayoutManager.canScrollVertically();
recyclerView.setLayoutManager(mLayoutManager);
adapter = new CommentAdapter(commentList, this);
/* download page 1*/
adapter.addHeader(header);
recyclerView.setAdapter(adapter);
getCommentList();
/* Scroll Listener which takes care of all triggers to download to load data to adapter based position of the view*/
// code for downloading more pages of comments
}
private void prepareHeader(View header) {
/* preparing the header*/
discussion_image = (ImageView) header.findViewById(R.id.discussion_image_1);
title = (TextView) header.findViewById(R.id.discussion_title);
commentno = (TextView) header.findViewById(R.id.comment_count);
description = (TextView) header.findViewById(R.id.discussion_text_content);
title.setText(discussion_title);
title.setTypeface(AppConstants.getTypeFaceBold(this));
description.setText(discussion_text);
discriptionText = discussion_text + "";
Linkify.addLinks(description, Linkify.WEB_URLS);
description.setTypeface(AppConstants.getTypeFaceNormal(this));
if (comment_count > 2) {
commentno.setText(String.valueOf(comment_count - 1) + " comments");
} else if (comment_count == 2){
commentno.setText(String.valueOf(comment_count - 1) + " comment");
}else {
commentno.setText("Be the first to comment");
}
if (discussion_image_url == null || discussion_image_url.equals("")) {
discussion_image.setVisibility(View.GONE);
//progressbar.setVisibility(View.GONE);
} else {
discussion_image.setVisibility(View.VISIBLE);
final String image_url = discussion_image_url;
if(UtilMethod.isStringNullOrBlank(image_url))
{
//progressbar.setVisibility(View.GONE);
}
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width=dm.widthPixels;
int height=dm.heightPixels;
Picasso.with(this)
.load(image_url)
.placeholder(R.drawable.default_img_big).error(R.drawable.default_img_big)
.transform(new ImageTransformation(width))
.into(discussion_image, new Callback() {
#Override
public void onSuccess() {
// TODO Auto-generated method stub
//progressbar.setVisibility(View.GONE);
}
#Override
public void onError() {
// TODO Auto-generated method stub
//progressbar.setVisibility(View.GONE);
}
});
discussion_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// code
}
});
}
}
The Adapter:
public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CustomViewHolder> {
ArrayList<CommentListBean> mArrayList;
Context mContext;
String event = "";
public static final int TYPE_HEADER = 111;
public static final int TYPE_FOOTER = 222;
public static final int TYPE_ITEM = 333;
//headers
List<View> headers = new ArrayList<>();
//footers
List<View> footers = new ArrayList<>();
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class CustomViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
private View view;
final TextView timestamp_tv;
final TextView chat_username;
final TextView description_tv;
final ImageView author_image_view;
final ImageView comment_image;
public CustomViewHolder(View v) {
super(v);
view = v;
chat_username = (TextView) v.findViewById(R.id.comment_author_chatname);
timestamp_tv = (TextView) v.findViewById(R.id.comment_timestamp);
description_tv = (TextView) v.findViewById(R.id.comment_text);
comment_image = (ImageView) v.findViewById(R.id.comment_image);
author_image_view = (ImageView) v.findViewById(R.id.comment_author_image);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public CommentAdapter(ArrayList<CommentListBean> arrayList, Context context) {
this.mContext = context;
this.mArrayList = arrayList;
}
// Create new views (invoked by the layout manager)
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
if (viewType == TYPE_ITEM) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_list_item, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
} else {
//create a new framelayout, or inflate from a resource
FrameLayout frameLayout = new FrameLayout(parent.getContext());
//make sure it fills the space
frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return new HeaderFooterViewHolder(frameLayout);
}
}
// Replace the contents of a view (invoked by the layout manager)
public void onBindViewHolder(final CustomViewHolder holder, final int position) {
//check what type of view our position is
if(position < headers.size()){
View v = headers.get(position);
//add our view to a header view and display it
prepareHeaderFooter((HeaderFooterViewHolder) holder, v);
}else if(position >= headers.size() + mArrayList.size()){
View v = footers.get(position-mArrayList.size()-headers.size());
//add oru view to a footer view and display it
prepareHeaderFooter((HeaderFooterViewHolder) holder, v);
}else {
// - code for normal comment view
}
}
#Override
public int getItemViewType(int position) {
//check what type our position is, based on the assumption that the order is headers > items > footers
if(position < headers.size()){
return TYPE_HEADER;
}else if(position >= headers.size() + mArrayList.size()){
return TYPE_FOOTER;
}
return TYPE_ITEM;
}
private void prepareHeaderFooter(HeaderFooterViewHolder vh, View view){
//empty out our FrameLayout and replace with our header/footer
vh.base.removeAllViews();
vh.base.addView(view);
}
//add a header to the adapter
public void addHeader(View header){
if(!headers.contains(header)){
headers.add(header);
//animate
notifyItemInserted(headers.size()-1);
}
}
//remove a header from the adapter
public void removeHeader(View header){
if(headers.contains(header)){
//animate
notifyItemRemoved(headers.indexOf(header));
headers.remove(header);
}
}
//add a footer to the adapter
public void addFooter(View footer){
if (!footers.contains(footer)){
footers.add(footer);
//animate
notifyItemInserted(headers.size()+mArrayList.size()+footers.size()-1);
}
}
//remove a footer from the adapter
public void removeFooter(View footer){
if(footers.contains(footer)) {
//animate
notifyItemRemoved(headers.size()+mArrayList.size()+footers.indexOf(footer));
footers.remove(footer);
}
}
//our header/footer RecyclerView.ViewHolder is just a FrameLayout
public static class HeaderFooterViewHolder extends CustomViewHolder{
FrameLayout base;
public HeaderFooterViewHolder(View itemView) {
super(itemView);
this.base = (FrameLayout) itemView;
}
}
}
XML for the header view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/margin_10">
<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:id="#+id/message_list_image_layout"
android:orientation="horizontal"
android:paddingTop="20dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="Representative image for the discussion"
android:background="#color/background_color"
android:id="#+id/discussion_image_1"
android:layout_marginBottom="#dimen/margin_5"
android:layout_marginTop="#dimen/margin_5"
android:src="#drawable/bg"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:maxHeight="280dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/discussion_title"
android:text="This is heading of the content"
android:layout_marginLeft="#dimen/margin_20"
android:layout_marginRight="#dimen/margin_20"
style="#style/Base.TextAppearance.AppCompat.Display1"
android:alpha="075" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/discussion_text_content"
android:layout_marginTop="#dimen/margin_10"
android:layout_marginLeft="#dimen/margin_20"
android:layout_marginRight="#dimen/margin_20"
android:text="this is the text of content. this is the text of content. this is the text of content. this is the text of content. this is the text of content.this is the text of content. this is the text of content. this is the text of content. this is the text of content. this is the text of content."
style="#style/Base.TextAppearance.AppCompat.Body1"
android:alpha="0.75" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="#dimen/margin_10"
android:layout_marginLeft="#dimen/margin_20"
android:layout_marginRight="#dimen/margin_20"
android:background="#color/dark_background_color"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginTop="#dimen/margin_10"
android:layout_marginBottom="#dimen/margin_10"
android:layout_marginRight="#dimen/margin_20"
android:layout_marginLeft="#dimen/margin_20"
android:gravity="center_vertical|right|end"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/comment_count"
android:text="4 comments" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Screenshots
Normal view
when I scroll a bit
I have a feeling that it has something to do with LinkMovementMethod. Please help.

Categories

Resources