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.
Related
i already success to make one Recyclerview and i want to add new Recyclerview Horizontal on top. i will explain in my code :
<android.support.v7.widget.RecyclerView
android:id="#+id/arrayListUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:divider="#color/white">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:id="#+id/arrayList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:divider="#color/white">
</android.support.v7.widget.RecyclerView>
id:arrayList is my first Recyclerview have name xml feeds_listview
id:arrayListUser is my new Recyclerview, i want make this Recyclerview Horizontal
xml for new Recylerview is feeds_listviewUser
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profil"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="30dp"
android:layout_gravity="center"
android:src="#drawable/cthprofil" />
<TextView
android:id="#+id/fullName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="5dp"
android:layout_marginBottom="20"
android:text="Megi Fernanda"
android:textSize="17sp"
android:textColor="#color/colordefault"
android:textStyle="bold" />
</LinearLayout>
and this is my class adapter
public class FeedsCustomAdapter extends RecyclerView.Adapter<FeedsCustomAdapter.ViewHolder> {
private Context context;
private List<FeedsAdapter> feeds_list;
private ArrayList<Feeds> mFeedsList = new ArrayList<Feeds>();
private OnItemClickListener mListener;
private OnItemClickListener mListener2;
public FeedsCustomAdapter(Context context, ArrayList<Feeds> mFeedsList) {
this.context = context;
this.mFeedsList = mFeedsList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.feeds_listview, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Feeds feed = getFeeds().get(position);
int textColor = context.getResources().getColor(R.color.btn_next);
int textColor2 = context.getResources().getColor(R.color.text_color_black);
holder.fullName.setText(feed.user.fullName);
holder.location.setText(feed.user.location);
holder.topic.setText(Html.fromHtml( "Menyelesaikan Tantangan " + " <font color = '" + String.valueOf(textColor2) + "'>" + feed.topic + "</font>" ) );
Picasso.with(context)
.load(feed.user.avatar)
.into(holder.profile);
PrettyTime prettyTime = new PrettyTime();
String times = prettyTime.format(DateUtil.timeMilisTodate(feed.timestamp * 1000));
holder.times.setText(times);
}
#Override
public int getItemCount() {
return mFeedsList.size();
}
public ArrayList<Feeds> getFeeds() {
return mFeedsList;
}
public void setComplete(int position) {
mFeedsList.get(position).isComplete = 1;
}
public boolean last() {
boolean result = false;
int total = mFeedsList.size();
for (int i = 0; i < mFeedsList.size(); i++) {
if (mFeedsList.get(i).isComplete == 1) {
total--;
}
}
if (total == 1) {
result = true;
}
return result;
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView fullName;
public TextView location;
public TextView topic;
public ImageView profile;
public TextView times;
public ViewHolder(View itemView) {
super(itemView);
fullName = (TextView) itemView.findViewById(R.id.fullName);
location = (TextView) itemView.findViewById(R.id.location);
topic = (TextView) itemView.findViewById(R.id.topic);
profile = (ImageView) itemView.findViewById(R.id.profil);
times = (TextView) itemView.findViewById(R.id.times);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mListener2 != null){
mListener2.onItemClick2(v ,getPosition());
}
}
});
topic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mListener != null){
mListener.onItemClick(v ,getPosition());
}
}
});
}
}
public void setClickListener(OnItemClickListener clickListener) {
this.mListener = clickListener;
}
public void setClickListenerProfile(OnItemClickListener clickListener2){
this.mListener2 = clickListener2;
}
public interface OnItemClickListener {
public abstract void onItemClick(View view, int position);
public abstract void onItemClick2(View view, int position);
}
so, in my code i success to display first recylerview with my first xml and i want add new recylerview horizontal with new xml feeds_listviewUser
You can use LinearLayout to wrap both recyclerView.
<android.support.v7.widget.RecyclerView
android:id="#+id/arrayListUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#color/white">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:id="#+id/arrayList"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="#color/white">
</android.support.v7.widget.RecyclerView>
And assign horizontal layout manager to one recyclerview and vertical layout manager to other
LinearLayoutManager userManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
arrayListUser.setLayoutManager(userManager);
LinearLayoutManager listManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
arrayList.setLayoutManager(listManager);
Put your recyclerviews in Relative layout.
First add horizontal recyclerView to alignParentTop true and fix height according to visibility of feeds_listviewUser next add vertical recyclerView with layout_below horizontal recyclerview id.
This question already has answers here:
Move layout up when soft keyboard is shown
(7 answers)
Closed 6 years ago.
I am having trouble pushing up the entire recycler view when the keyboard is diplayed, it cuts off the message that is previous. I am create a chat view that looks like this xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/commentsParentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/noCommentsResults"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/lineSep"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="#string/noCommentsFound"
android:textSize="20sp"
android:visibility="gone" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/pullToLoadMore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/lineSep"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="50dp"
android:paddingBottom="10dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/comments_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
/>
</android.support.v4.widget.SwipeRefreshLayout>
<View
android:id="#+id/lineSep"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_above="#+id/commentsAddLayout"
android:background="#color/horizontalLine" />
<LinearLayout
android:id="#+id/commentsAddLayout"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:id="#+id/emojiSelector"
android:layout_width="0dp"
android:layout_height="36dp"
android:layout_weight="1"
android:src="#drawable/emoji" />
<EditText
android:id="#+id/commentText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="4"
android:background="#android:color/transparent"
android:hint="#string/add_comment"
android:maxLength="150" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#color/horizontalLine" />
<TextView
android:id="#+id/sendComment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/send"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
And this is my recycler view code:
private void setupAdapter() {
//stops lag for recycler view for load
commentsRecyclerView.setHasFixedSize(true);
commentsAdapter = new CommentsAdapter(this, dbCommentsList, TypeFaceProvider.getTypeFace(this, 0),
TypeFaceProvider.getTypeFace(this, 1), TypeFaceProvider.getTypeFace(this, 2));
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
commentsRecyclerView.setLayoutManager(mLayoutManager);
commentsRecyclerView.setItemAnimator(new DefaultItemAnimator());
commentsAdapter.setOnEntryClickListener(new CommentsAdapter.OnEntryClickListener() {
#Override
public void onEntryClick(View view, int position) {
DatabaseComment comment = dbCommentsList.get(position);
TextView deleteBtn = (TextView) view.findViewById(R.id.commentUserRemove);
if (view == deleteBtn) {
//used to remove the comment from db and the list
db.removeSingleComment(comment);
dbCommentsList.remove(position);
commentsAdapter.notifyDataSetChanged();
} else {
takeToUserProfile(dbCommentsList.get(position));
}
}
});
commentsRecyclerView.setAdapter(commentsAdapter);
commentsRecyclerView.scrollToPosition(0);
hideProgressDialog();
}
This is my comments adapter:
public class CommentsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static OnEntryClickListener mOnEntryClickListener;
private List<DatabaseComment> dbCommentsList;
private Typeface typeFace, italicTypeface, boldTypeface;
public CommentsAdapter(Context mContext, List<DatabaseComment> comments, Typeface myTypeface, Typeface myTypefaceItalic, Typeface myTypefaceBold) {
Context context = mContext;
dbCommentsList = comments;
typeFace = myTypeface;
italicTypeface = myTypefaceItalic;
boldTypeface = myTypefaceBold;
}
public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {
mOnEntryClickListener = onEntryClickListener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
return new MyFeatureViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.comment_business_item, parent, false));
case 1:
return new MyViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.comment_user_item, parent, false));
}
return new MyViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.comment_user_item, parent, false));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int pos = getItemViewType(position);
//is a business comment
if (pos == 0) {
MyFeatureViewHolder featureViewHolder = (MyFeatureViewHolder) holder;
DatabaseComment dbComment = dbCommentsList.get(position);
featureViewHolder.commentCompany.setTypeface(boldTypeface);
featureViewHolder.commentCompanyMsg.setTypeface(typeFace);
featureViewHolder.commentCompanyDate.setTypeface(italicTypeface);
featureViewHolder.commentCompany.setText(dbComment.getUsername());
featureViewHolder.commentCompanyMsg.setText(dbComment.getCommentText());
Calendar date = Calendar.getInstance();
date.setTimeInMillis(dbComment.getCommentDate());
int newMonth = date.get(Calendar.MONTH) + 1;
String commentDateTxt = (newMonth + "." + date.get(Calendar.DAY_OF_MONTH) + "." + date.get(Calendar.YEAR));
featureViewHolder.commentCompanyDate.setText(commentDateTxt);
}
//anything greater than 0 is a user comment - with emoji
if (pos == 1) {
MyViewHolder myViewHolder = (MyViewHolder) holder;
if (dbCommentsList.get(position).getIsChanged() == 1) {
myViewHolder.commentUserRemove.setVisibility(View.VISIBLE);
} else {
myViewHolder.commentUserRemove.setVisibility(View.GONE);
}
DatabaseComment dbComment = dbCommentsList.get(position);
myViewHolder.commentUsername.setTypeface(boldTypeface);
myViewHolder.commentUserMsg.setTypeface(typeFace);
myViewHolder.commentUserDate.setTypeface(italicTypeface);
myViewHolder.commentUsername.setText(dbComment.getUsername());
myViewHolder.commentUserMsg.setText(dbComment.getCommentText());
Calendar date = Calendar.getInstance();
date.setTimeInMillis(dbComment.getCommentDate());
//Note only one plus one because of new comments added will
int newMonth = date.get(Calendar.MONTH) + 1;
String commentDateTxt = (newMonth + "." + date.get(Calendar.DAY_OF_MONTH) + "." + date.get(Calendar.YEAR));
myViewHolder.commentUserDate.setText(commentDateTxt);
int[] commentsImageList = new int[]{R.drawable.e1, R.drawable.e1, R.drawable.e2, R.drawable.e3, R.drawable.e4,
R.drawable.e5, R.drawable.e6, R.drawable.e7, R.drawable.e8, R.drawable.e9, R.drawable.e10,
R.drawable.e11, R.drawable.e12, R.drawable.e13, R.drawable.e14,
R.drawable.e15, R.drawable.e16, R.drawable.e17, R.drawable.e18, R.drawable.e19};
myViewHolder.emojiIcon.setImageResource(commentsImageList[dbComment.getIsType()]);
}
}
#Override
public int getItemCount() {
return dbCommentsList.size();
}
#Override
public int getItemViewType(int position) {
if (dbCommentsList.get(position).getIsType() == 0) {
return 0;
} else {
return 1;
}
}
public interface OnEntryClickListener {
void onEntryClick(View view, int position);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView commentUsername, commentUserMsg, commentUserDate, commentUserRemove;
public ImageView emojiIcon;
public MyViewHolder(View view) {
super(view);
commentUsername = (TextView) view.findViewById(R.id.commentUsername);
commentUserMsg = (TextView) view.findViewById(R.id.commentUserMsg);
commentUserDate = (TextView) view.findViewById(R.id.commentUserDate);
commentUserRemove = (TextView) view.findViewById(R.id.commentUserRemove);
emojiIcon = (ImageView) view.findViewById(R.id.emojiIcon);
view.setOnClickListener(this);
commentUserRemove.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mOnEntryClickListener != null) {
mOnEntryClickListener.onEntryClick(v, getAdapterPosition());
}
}
}
public class MyFeatureViewHolder extends RecyclerView.ViewHolder {
public TextView commentCompany, commentCompanyMsg, commentCompanyDate;
public ImageView emojiIcon;
public MyFeatureViewHolder(View view) {
super(view);
commentCompany = (TextView) view.findViewById(R.id.commentCompany);
commentCompanyMsg = (TextView) view.findViewById(R.id.commentCompanyMsg);
commentCompanyDate = (TextView) view.findViewById(R.id.commentCompanyDate);
emojiIcon = (ImageView) view.findViewById(R.id.emojiIcon);
}
}
}
So when the edit text box is selected the messages in the list view do not move up, but the SEND button and the rest do - so not sure what I need to do to push up the comments view? It looks like I might have a layout issue - but trying the answers in the other questions have not solved it for me:
Solution 1:
The adjustpan pushes the view up too high going over the battery and time in the status bar and slightly cutting off the bottom of the view when the keyboard pops up.
Solution 2:
The adjustresize does nothing the view still stays the same.
If you want to resize your content when the softkeyboard opened, use adjust resize
<application ... >
<activity
android:windowSoftInputMode="adjustResize" ... >
...
</activity>
...
</application>
or if you want your screen pushed to top, use adjustPan in your manifest
<application ... >
<activity
android:windowSoftInputMode="adjustPan" ... >
...
</activity>
...
</application>
I have implemented a gridlayout using recycler view . I need to implement the native ad in between of the grid items. I tried it but i was getting the native ads on top of my gridview items.
public class Event_Discover_Combined_Adapter extends RecyclerView.Adapter<Event_Discover_Combined_Adapter.MyViewHolder> {
private Context context;
private ArrayList<Event_Discover_Combined_Details> beanList;
private int itemCount;
public Event_Discover_Combined_Adapter(Context context, ArrayList<Event_Discover_Combined_Details> beanList, int itemCount) {
this.context = context;
this.beanList = beanList;
this.imageLoader = ImageLoader.getInstance();
this.itemCount = itemCount;
}
//int viewType ;
#Override
public int getItemViewType(int position) {
if (position % 3 == 0) {
return R.layout.native_ad_frame_layout;
} else {
if (beanList.get(position).getType() == ConstantUrl.TYPE_EVENT) {
return R.layout.events_item;
} else {
return R.layout.discover_item;
}
}
}
#Override
public Event_Discover_Combined_Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(context).inflate(viewType, parent, false);
return new MyViewHolder(itemView);
}
public static ImageLoader imageLoader;
// public static ImageLoader imageLoader2;
#Override
public void onBindViewHolder(final Event_Discover_Combined_Adapter.MyViewHolder holder, int position) {
Event_Discover_Combined_Details bean = beanList.get(position);
if (position % 3 == 0) {
//Ad View
//For Native Ads
AdLoader.Builder builder = new AdLoader.Builder(context, context.getResources().getString(R.string.ADMOB_AD_UNIT_ID));
//if (requestContentAds) {
builder.forContentAd(new NativeContentAd.OnContentAdLoadedListener() {
#Override
public void onContentAdLoaded(NativeContentAd ad) {
NativeContentAdView adView = (NativeContentAdView) getLayoutInflater()
.inflate(R.layout.native_ad_content, null);
populateContentAdView(ad, adView);
holder.frameLayout.removeAllViews();
holder.frameLayout.addView(adView);
}
});
//}
AdLoader adLoader = builder.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(context, "Failed to load native ad: "
+ errorCode, Toast.LENGTH_SHORT).show();
}
}).build();
adLoader.loadAd(new AdRequest.Builder().build());
} else {
//Normal View
AppLog.Log("combine", "beanlist" + bean.getType());
if (bean.getType() == ConstantUrl.TYPE_DISCOVER) {
if (!bean.getDiscoverDetails().getIcon().equals(""))
imageLoader.displayImage(bean.getDiscoverDetails().getIcon(),
holder.iv_discover_icon);
holder.tv_author_name.setText(bean.getDiscoverDetails().getAuthor());
holder.item_discover_descrip.setText(bean.getDiscoverDetails().getDescription());
holder.tv_discover_heading.setText(bean.getDiscoverDetails().getTitle());
} else if (bean.getType() == ConstantUrl.TYPE_EVENT) {
if (!bean.getEventDetails().getIcon().equals(""))
imageLoader.displayImage(bean.getEventDetails().getIcon(),
holder.event_icon);
/* holder.item_event_date.setText(bean.getStartDate());
holder.item_event_time.setText(bean.getStartDate());*/
try {
Date date1 = AppUtils.getFormatedDate(bean.getEventDetails().getStartDate());
String event_time = (String) android.text.format.DateFormat.format("EEEE", date1) + " " + context.getString(R.string.at_text) + " " + new SimpleDateFormat("hh:mm aa").format(date1);
// holder.item_event_date.setText((String) android.text.format.DateFormat.format("dd", date1));
holder.item_event_date.setText(event_time);
holder.item_event_time.setText(event_time);
} catch (Exception e) {
e.printStackTrace();
}
holder.item_event_heading.setText(bean.getEventDetails().getName());
holder.item_event_descrip.setText(bean.getEventDetails().getDescription());
}
}
}
#Override
public int getItemCount() {
return itemCount;
}
// int count = 0;
public void setItemCount(int count) {
this.itemCount = count;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//For Discover
public ImageView iv_discover_icon;
MyTextView tv_author_name;
MyTextView item_discover_descrip;
MyTextView_medium tv_discover_heading;
//For Events
public ImageView event_icon;
public MyTextView_medium item_event_time;
MyTextView item_event_date;
MyTextView item_event_descrip;
MyTextView_medium item_event_heading;
//For Native Ads
FrameLayout frameLayout;
public MyViewHolder(final View itemView) {
super(itemView);
//For Discover
iv_discover_icon = (ImageView) itemView.findViewById(R.id.iv_discover_icon);
tv_author_name = (MyTextView) itemView.findViewById(R.id.tv_author_name);
tv_discover_heading = (MyTextView_medium) itemView.findViewById(R.id.tv_discover_heading);
item_discover_descrip = (MyTextView) itemView.findViewById(R.id.item_discover_descrip);
itemView.setOnClickListener(this);
//For Events
event_icon = (ImageView) itemView.findViewById(R.id.event_icon);
item_event_date = (MyTextView) itemView.findViewById(R.id.item_event_date);
item_event_time = (MyTextView_medium) itemView.findViewById(R.id.item_event_time);
item_event_heading = (MyTextView_medium) itemView.findViewById(R.id.item_event_heading);
item_event_descrip = (MyTextView) itemView.findViewById(R.id.item_event_descrip);
itemView.setOnClickListener(this);
//For Native Ads
frameLayout = (FrameLayout) itemView.findViewById(R.id.fl_adplaceholder);
}
#Override
public void onClick(View v) {
if ((beanList.get(getAdapterPosition()).getType()) == ConstantUrl.TYPE_EVENT) {
Intent i = new Intent(context, Events.class);
i.putExtra("event_details", beanList.get(getAdapterPosition()).getEventDetails());
context.startActivity(i);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(beanList.get(getAdapterPosition()).getDiscoverDetails().getUrl()));
context.startActivity(intent);
}
}
}
private LayoutInflater getLayoutInflater() {
AppLog.Log("classmate5", "inside_getLayoutInflater" + LayoutInflater.from(context));
return LayoutInflater.from(context);
}
private void populateContentAdView(NativeContentAd nativeContentAd,
NativeContentAdView adView) {
AppLog.Log("classmate5", "inside_populateContentAdView");
adView.setHeadlineView(adView.findViewById(R.id.contentad_headline));
adView.setImageView(adView.findViewById(R.id.contentad_image));
adView.setBodyView(adView.findViewById(R.id.contentad_body));
adView.setCallToActionView(adView.findViewById(R.id.contentad_call_to_action));
adView.setLogoView(adView.findViewById(R.id.contentad_logo));
adView.setAdvertiserView(adView.findViewById(R.id.contentad_advertiser));
// Some assets are guaranteed to be in every NativeContentAd.
((TextView) adView.getHeadlineView()).setText(nativeContentAd.getHeadline());
((TextView) adView.getBodyView()).setText(nativeContentAd.getBody());
((TextView) adView.getCallToActionView()).setText(nativeContentAd.getCallToAction());
((TextView) adView.getAdvertiserView()).setText(nativeContentAd.getAdvertiser());
List<NativeAd.Image> images = nativeContentAd.getImages();
if (images.size() > 0) {
((ImageView) adView.getImageView()).setImageDrawable(images.get(0).getDrawable());
}
// Some aren't guaranteed, however, and should be checked.
NativeAd.Image logoImage = nativeContentAd.getLogo();
if (logoImage == null) {
adView.getLogoView().setVisibility(View.INVISIBLE);
} else {
((ImageView) adView.getLogoView()).setImageDrawable(logoImage.getDrawable());
adView.getLogoView().setVisibility(View.VISIBLE);
}
// Assign native ad object to the native view.
adView.setNativeAd(nativeContentAd);
}
}
I am not able to figure out where to keep to check and how to add native ads in between the items of my gridview (recyclerview).
Layout of my discover item where I am having a framelayout. In this framelayout I am loading the native ads.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical">
<ImageView
android:id="#+id/iv_discover_icon"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:scaleType="centerCrop"
android:src="#drawable/events" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
android:background="#color/white"
android:orientation="vertical">
<com.erbauen.widgets.MyTextView_medium
android:id="#+id/tv_discover_heading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/item_event_detail"
android:alpha="0.6"
android:lines="2"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:text="Network over Coffee"
android:textColor="#color/black"
android:textSize="#dimen/events_item_date_time"
/>
<com.erbauen.widgets.MyTextView
android:id="#+id/tv_author_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/item_event_detail"
android:layout_marginTop="2dp"
android:alpha="0.6"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:singleLine="true"
android:text="Network over Coffee"
android:textColor="#color/black"
android:textSize="#dimen/events_item_date_time"
/>
<com.erbauen.widgets.MyTextView
android:id="#+id/item_discover_descrip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_event_heading"
android:layout_marginTop="1dp"
android:fontFamily="Helvetica"
android:maxLines="2"
android:singleLine="false"
android:text="Brief information about the event. Brief information about the event. Brief information about the event."
android:textSize="#dimen/events_item_date_time"
android:visibility="gone" />
</LinearLayout>
</LinearLayout>
<!--<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:alpha="0.5"
android:background="#color/light_green">
</View>-->
</android.support.v7.widget.CardView>
I removed the framelayout from the discover_item.xml. Now how to hide and unhide the respective layouts ?
You need to remove ad from your card layout or alternatively you can hide and show your views on the basis of row number.
And you need to create a different cardlayout with ad only and need to show it for every 3rd position from your onBindViewHolder method
if (position % 3 == 0) {
// inflate your ad view here or hide your normal native view here and show ad view
} else {
// inflate your normal native view here or hide your ad view here and show normal native view
}
I am trying to create a ListView, each row of which is a horizontal scrolling list. Earlier, I was using HorizontalScrollView but I needed a layout which could recycle views. So I used RecyclerView, but now the contents of RecyclerView are not visible.
Here is my adapter for vertical listview:
public class FeedAdapter extends BaseAdapter {
private Context context;
private FeedItem feedItem;
private static LayoutInflater inflater = null;
private Picasso picasso;
Typeface opensans;
public FeedAdapter(Context context, FeedItem feedItem) {
this.context = context;
this.feedItem = feedItem;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
opensans = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
OkHttpClient okHttpClient = new OkHttpClient();
picasso = new Picasso.Builder(context)
.downloader(new OkHttpDownloader(okHttpClient))
.build();
}
#Override
public int getCount() {
return feedItem.getFeedList().size();
}
#Override
public FeedList getItem(int position) {
return feedItem.getFeedList().get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final FeedRowViewHolder rowViewHolder;
if (view == null) {
view = inflater.inflate(R.layout.feed_row, parent, false);
rowViewHolder = new FeedRowViewHolder(view);
view.setTag(rowViewHolder);
} else {
rowViewHolder = (FeedRowViewHolder) view.getTag();
}
final FeedList feedList = feedItem.getFeedList().get(position);
picasso.with(context)
.load(feedList.getThumbnailUrl())
.resize(120, 120)
.centerCrop()
.into(rowViewHolder.galleryThumb);
rowViewHolder.galleryThumb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String api_url = feedList.getUrl();
String delims = "/";
String[] tokens = api_url.split(delims);
String thumbId = tokens[5];
((HomeActivity) context).changeIntent(thumbId);
}
});
rowViewHolder.galleryName.setText(feedList.getGalleryName());
rowViewHolder.galleryName.setTypeface(opensans);
rowViewHolder.galleryName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String api_url = feedList.getUrl();
String delims = "/";
String[] tokens = api_url.split(delims);
String thumbId = tokens[5];
((HomeActivity) context).changeIntent(thumbId);
}
});
rowViewHolder.timestamp.setText(feedList.getCreatedDate());
rowViewHolder.timestamp.setTypeface(opensans);
rowViewHolder.followButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
picasso.with(context)
.load(R.drawable.cta_button_follow_secondary_state)
.into(rowViewHolder.followButton);
}
});
LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
rowViewHolder.recyclerView.setLayoutManager(layoutManager);
FeedItemAdapter adapter = new FeedItemAdapter(context, feedList.getPhotos());
rowViewHolder.recyclerView.setAdapter(adapter);
return view;
}
static class FeedRowViewHolder {
#Bind(R.id.imageView75)
ImageView galleryThumb;
#Bind(R.id.textView65)
TextView galleryName;
#Bind(R.id.textView66)
TextView timestamp;
#Bind(R.id.imageView162)
ImageView followButton;
#Bind(R.id.recyclerView)
RecyclerView recyclerView;
public FeedRowViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
Here is my adapter for Horizontal RecyclerView:
public class FeedItemAdapter extends RecyclerView.Adapter<FeedItemAdapter.ViewHolder> {
private List<Photo> list;
private Context context;
private Picasso picasso;
Typeface opensans;
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Photo photo = getValueAt(position);
picasso.with(context)
.load(photo.getPhotoUrl())
.resize(1020, 768)
.centerCrop()
.into(holder.image);
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String photo_url = photo.getPhoto();
String delims = "/";
String[] tokens = photo_url.split(delims);
String photoId = tokens[5];
((HomeActivity) context).setBackImage(photoId);
}
});
picasso.with(context)
.load(photo.getProfilePic())
.resize(120, 120)
.centerCrop()
.transform(new CircleTransform())
.into(holder.profilePic);
holder.profilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user_url = photo.getOwner();
String delims = "/";
String[] tokens = user_url.split(delims);
String photoId = tokens[5];
((HomeActivity) context).showUserProfile(photoId);
}
});
holder.commentButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((HomeActivity) context).showComments();
}
});
holder.fiveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((HomeActivity) context).showLikes();
}
});
holder.commentImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((HomeActivity) context).showComments();
}
});
holder.username.setText(photo.getUserName());
holder.username.setTypeface(opensans);
holder.userFives.setText(Integer.toString(photo.getUserFives()) + " Fives");
holder.userFives.setTypeface(opensans);
holder.caption.setText(photo.getCaption());
holder.caption.setTypeface(opensans);
final int[] fives = {photo.getPhotoFives()};
holder.numFives.setText(Integer.toString(photo.getPhotoFives()));
holder.numFives.setTypeface(opensans);
holder.numComments.setText(Integer.toString(photo.getNumComments()));
holder.numComments.setTypeface(opensans);
final boolean[] liked = {false};
holder.fiveButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
holder.fiveButton.setText("Hi Fiveeed!");
holder.fiveButton.setTypeface(opensans);
holder.fiveButton.setTextColor(Color.parseColor("#FAC80A"));
picasso.with(context)
.load(R.drawable.cta_ic_five_pressed_state)
.into(holder.fiveImage);
}
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
holder.fiveButton.setText("Five This!");
holder.fiveButton.setTypeface(opensans);
holder.fiveButton.setTextColor(Color.parseColor("#707070"));
picasso.with(context)
.load(R.drawable.user_profile_activity_1_ic_five_count)
.into(holder.fiveImage);
}
if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
holder.fiveButton.setText("Five This!");
holder.fiveButton.setTypeface(opensans);
holder.fiveButton.setTextColor(Color.parseColor("#707070"));
picasso.with(context)
.load(R.drawable.user_profile_activity_1_ic_five_count)
.into(holder.fiveImage);
}
return false;
}
});
holder.fiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (liked[0] == false) {
holder.fiveButton.setText("Hi Fived!");
holder.fiveButton.setTypeface(opensans);
holder.fiveButton.setTextColor(Color.parseColor("#FAC80A"));
holder.numFives.setText(Integer.toString(fives[0] + 1));
fives[0] = fives[0] + 1;
picasso.with(context)
.load(R.drawable.cta_ic_five_pressed_state)
.into(holder.fiveImage);
liked[0] = true;
} else {
holder.fiveButton.setText("Five This!");
holder.fiveButton.setTypeface(opensans);
holder.fiveButton.setTextColor(Color.parseColor("#707070"));
holder.numFives.setText(Integer.toString(fives[0] - 1));
fives[0] = fives[0] - 1;
picasso.with(context)
.load(R.drawable.user_profile_activity_1_ic_five_count)
.into(holder.fiveImage);
liked[0] = false;
}
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public Photo getValueAt(int position) {
return list.get(position);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.imageView86)
ImageView image;
#Bind(R.id.imageView76)
ImageView profilePic;
#Bind(R.id.textView67)
TextView username;
#Bind(R.id.textView68)
TextView userFives;
#Bind(R.id.textView1)
TextView caption;
#Bind(R.id.textView69)
TextView fiveButton;
#Bind(R.id.textView71)
TextView commentButton;
#Bind(R.id.imageView77)
ImageView fiveImage;
#Bind(R.id.textView72)
TextView numFives;
#Bind(R.id.imageView120)
ImageView commentImage;
#Bind(R.id.textView73)
TextView numComments;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public FeedItemAdapter(Context context, List<Photo> list) {
this.context = context;
this.list = list;
opensans = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
OkHttpClient okHttpClient = new OkHttpClient();
picasso = new Picasso.Builder(context)
.downloader(new OkHttpDownloader(okHttpClient))
.build();
}
}
Here is my layout for row of listview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scroller_placeholder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#231f20"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linearLayout7"
android:background="#343031"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView75"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:paddingRight="5dp"
android:src="#drawable/user_profile_activity_1_img_gallery_1_icon"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imageView75"
android:orientation="vertical"
android:paddingLeft="5dp">
<TextView
android:id="#+id/textView65"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:alpha="0.8"
android:paddingBottom="2dp"
android:text="Wilderness"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/textView66"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:text="2 hrs."
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#707070"
android:textSize="12sp" />
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView162"
android:src="#drawable/cta_button_follow_default_state"
android:layout_alignParentEnd="true"
android:layout_marginRight="20dp"
android:layout_centerVertical="true" />
</RelativeLayout>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The items for each row were getting displayed perfectly fine when I was using HorizontalScrollView but the contents of recyclerView are not getting displayed. I can't figure out what is the problem. Any help would be highly appreciated.
I think your problem is here RecyclerView's android:layout_height="wrap_content". Try to set this attribute to specific value.
Update
New release of Android Support Library 23.2:
The RecyclerView widget provides an advanced and flexible base for
creating lists and grids as well as supporting animations. This
release brings an exciting new feature to the LayoutManager API:
auto-measurement! This allows a RecyclerView to size itself based on
the size of its contents. This means that previously unavailable
scenarios, such as using WRAP_CONTENT for a dimension of the
RecyclerView, are now possible. You’ll find all built in
LayoutManagers now support auto-measurement.
As mr.icetea said you need to set the layout-height to a specific amount. You could get the shown items height and pass that on to the layout-height param.
https://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html documentation for adding layoutparams on the fly.
check out this method to calculate recyclerview height dynamically
// calculating height of Recycler view
private int calculateHeight(int size,int viewHeight) {
final float scale = mContext.getResources().getDisplayMetrics().density;
int singleViewHeight = (int) (viewHeight * scale + 0.5f);
int totalHeight = singleViewHeight * size;
return totalHeight;
}
and set height to recyclerview as-
//get recyclerview height
int height = calculateHeight(firstParam, secondparam);
ViewGroup.LayoutParams params = recyclerView.getLayoutParams();
params.height = height;
firstparam is sizofYourDataList_or_Array and secondparam is height of your row for recyclerview(so you have to give height for your row layout and that wiil be your second parameter's value)
below is my code which works fine for showing listview horizontally. how can I change it to gridvew. What changes should I make to change it to gridview? help me please
public class fifthscreen extends Activity {
int IOConnect = 0;
String _response;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String URL, URL2;
String SelectMenuAPI;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
String name;
String url1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
new TheTask().execute();
}
public class TheTask extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
try {
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json2 = new JSONObject(result);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
listview.setAdapter(cla);
}
}
}
public class CategoryListAdapter3 extends BaseAdapter {
private Activity activity;
private AQuery androidAQuery;
public CategoryListAdapter3(Activity act) {
this.activity = act;
// imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return fifthscreen.Category_ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
androidAQuery = new AQuery(getcontext());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.viewitem2, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.title2);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.image2);
holder.txtText.setText(fifthscreen.Category_name.get(position));
// imageLoader.DisplayImage(fifthscreen.Category_image.get(position),
activity, holder.imgThumb);
androidAQuery.id(holder.imgThumb).image(fifthscreen.Category_image.get(position), false,
false);
return convertView;
}
private Activity getcontext() {
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}
<!--- fifithscreen.xml--->
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_below="#+id/test_button_text5"
android:orientation="vertical" >
<com.example.examplecode.HorizontalListView
android:id="#+id/listview2"
android:layout_width="wrap_content"
android:layout_height="120dp"
android:layout_below="#+id/test_button_text5"
android:background="#ffffff"/>
</LinearLayout>
<!--viewitem2.xml--->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<ImageView
android:id="#+id/image2"
android:layout_width="90dp"
android:layout_height="70dp"
android:scaleType="fitXY"
android:padding="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:src="#drawable/ic_launcher"
/>
<TextView
android:id="#+id/title2"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:textColor="#000"
android:paddingTop="10dp"
android:gravity="center_horizontal"
/>
</LinearLayout>
No change at all. Just set adapter of GridView as your are setting for ListView.
I'd suggest that you use RecyclerView intead.
You might want to refer to the documentation and learn more about it.
I'm sharing my piece of code in which I'm changing my gridview to listview using RecyclerView
If you're using Android Studio then you might need to add dependencies in gradle build. In my case I added as follows:
dependencies {
.
.
.
compile 'com.android.support:recyclerview-v7:24.0.0'
}
First I'm defining a grid cell which is to be used in grid layout
recycler_cell.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView2"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:background="#FF000000"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView2"
android:layout_below="#+id/imageView2"
android:layout_alig=nParentStart="true"
android:layout_alignEnd="#+id/imageView2"
android:gravity="center"/>
</RelativeLayout>
Now I'm defining a list row which is to be used in list layout
recycler_row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:background="#FF000000"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignBottom="#+id/imageView"
android:layout_alignParentEnd="true"
android:layout_toEndOf="#+id/imageView"
android:gravity="center_vertical"
android:background="#FF333333"
android:textColor="#FFF"
android:padding="10dp"/>
</RelativeLayout>
recycler_view_test.xml
And of course define a layout which would contain RecyclerView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerView"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:layout_centerHorizontal="true"
>
</android.support.v7.widget.RecyclerView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Layout"
android:id="#+id/btnChange"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="62dp"/>
</RelativeLayout>
I'm sharing my piece of code but I'd strongly recommend that you go through the documentation and tutorials to understand RecyclerView to its full extent.
public class RecyclerViewTest extends AppCompatActivity
{
final int GRID = 0;
final int LIST = 1;
int type;
RecyclerView recyclerView;
RecyclerView.LayoutManager gridLayoutManager, linearLayoutManager;
MyAdapter adapter;
Button btnChange;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view_test);
// Display contents in views
final List<Person> list = new ArrayList<>();
list.add(new Person("Ariq Row 1"));
list.add(new Person("Ariq Row 2"));
list.add(new Person("Ariq Row 3"));
// Finding views by id
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
btnChange = (Button) findViewById(R.id.btnChange);
// Defining Linear Layout Manager
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
// Defining Linear Layout Manager (here, 3 column span count)
gridLayoutManager = new GridLayoutManager(getApplicationContext(), 3);
//Setting gird view as default view
type = GRID;
adapter = new MyAdapter(list, GRID);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(adapter);
//Setting click listener
btnChange.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if (type == LIST)
{
// Change to grid view
adapter = new MyAdapter(list, GRID);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(adapter);
type = GRID;
}
else
{
// Change to list view
adapter = new MyAdapter(list, LIST);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
type = LIST;
}
}
});
}
}
//Defining Adapter
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
List<Person> list;
int type;
final int GRID = 0;
final int LIST = 1;
MyAdapter(List<Person> list, int type)
{
this.list = list;
this.type = type;
}
// Inflating views if the existing layout items are not being recycled
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView;
if (viewType == GRID)
{
// Inflate the grid cell as a view item
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_cell, parent, false);
}
else
{
// Inflate the list row as a view item
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
}
return new ViewHolder(itemView, viewType);
}
// Add data to your layout items
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
Person person = list.get(position);
holder.textView.setText(person.name);
}
// Number of items
#Override
public int getItemCount()
{
return list.size();
}
// Using the variable "type" to check which layout is to be displayed
#Override
public int getItemViewType(int position)
{
if (type == GRID)
{
return GRID;
}
else
{
return LIST;
}
}
// Defining ViewHolder inner class
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView textView;
final int GRID = 0;
final int LIST = 1;
public ViewHolder(View itemView, int type)
{
super(itemView);
if (type == GRID)
{
textView = (TextView) itemView.findViewById(R.id.textView2);
}
else
{
textView = (TextView) itemView.findViewById(R.id.textView);
}
}
}
}
// Data Source Class
class Person
{
String name;
Person(String name)
{
this.name = name;
}
}
If you end up with the issue to auto fit the number of columns in case of grid layout then you might want to check #s-marks's answer in which he extended the GridLayoutManager class and added his own patch of code, and also my fix if you start having weird column width.
In my case, using his solution I made a class as follows:
class GridAutofitLayoutManager extends GridLayoutManager
{
private int mColumnWidth;
private boolean mColumnWidthChanged = true;
public GridAutofitLayoutManager(Context context, int columnWidth)
{
/* Initially set spanCount to 1, will be changed automatically later. */
super(context, 1);
setColumnWidth(checkedColumnWidth(context, columnWidth));
}
public GridAutofitLayoutManager(Context context, int columnWidth, int orientation, boolean reverseLayout)
{
/* Initially set spanCount to 1, will be changed automatically later. */
super(context, 1, orientation, reverseLayout);
setColumnWidth(checkedColumnWidth(context, columnWidth));
}
private int checkedColumnWidth(Context context, int columnWidth)
{
if (columnWidth <= 0)
{
/* Set default columnWidth value (48dp here). It is better to move this constant
to static constant on top, but we need context to convert it to dp, so can't really
do so. */
columnWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48,
context.getResources().getDisplayMetrics());
}
else
{
columnWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, columnWidth,
context.getResources().getDisplayMetrics());
}
return columnWidth;
}
public void setColumnWidth(int newColumnWidth)
{
if (newColumnWidth > 0 && newColumnWidth != mColumnWidth)
{
mColumnWidth = newColumnWidth;
mColumnWidthChanged = true;
}
}
#Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state)
{
int width = getWidth();
int height = getHeight();
if (mColumnWidthChanged && mColumnWidth > 0 && width > 0 && height > 0)
{
int totalSpace;
if (getOrientation() == VERTICAL)
{
totalSpace = width - getPaddingRight() - getPaddingLeft();
}
else
{
totalSpace = height - getPaddingTop() - getPaddingBottom();
}
int spanCount = Math.max(1, totalSpace / mColumnWidth);
setSpanCount(spanCount);
mColumnWidthChanged = false;
}
super.onLayoutChildren(recycler, state);
}
}
Then you simply have to change:
gridLayoutManager = new GridLayoutManager(getApplicationContext(), 3);
and use your custom grid layout object, here 100 is the width of columns in dp
gridLayoutManager = new GridAutofitLayoutManager(getApplicationContext(), 100);
You can do something like this:
For the layout of the grid/list use a merge:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ViewStub android:id="#+id/list"
android:inflatedId="#+id/showlayout"
android:layout="#layout/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
<ViewStub android:id="#+id/grid"
android:inflatedId="#+id/showlayout"
android:layout="#layout/grid_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
</merge>
then define the layout for the list and the grid (and also for their items), and manage the passage between them inflating the layouts, and then use a method like this to change the current view:
private void changeView() {
//if the current view is the listview, passes to gridview
if(list_visibile) {
listview.setVisibility(View.GONE);
gridview.setVisibility(View.VISIBLE);
list_visibile = false;
setAdapters();
}
else {
gridview.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
list_visibile = true;
setAdapters();
}
}
If you need the complete code, it is available in this article:
http://pillsfromtheweb.blogspot.it/2014/12/android-passare-da-listview-gridview.html
Just take a GridView object instead of Listview like :
GridView gridView;
gridView= (GridView) this.findViewById(R.id.gridView1);
And in you getView method of CategoryListAdapter3 do like :
convertView = inflater.inflate(R.layout.your_grid_item_leyout, null);
And at last in onPostExecute of TheTask do like :
gridView.setAdapter(cla);
That's It.
Use GridView instead of below:
Then replace
listview = (HorizontalListView) this.findViewById(R.id.listview2);
to
GridView gridview;
gridview=(GridView) findViewById(R.id.gridview);
Everything else are fine, just set Adapter using GridView object. And you are done.