I'm using Recyclerview in one of my activity, but I'm not able to show any data in recyclerView.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:id="#+id/toolBar">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_back_light"
android:layout_gravity="center"
android:layout_marginStart="16dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sushi"
android:textColor="#color/white"
android:textStyle="bold"
android:layout_gravity="center"
android:layout_marginStart="12dp"
android:textSize="18sp"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/chatMessages"
android:clipToPadding="false"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:layout_below="#+id/toolBar"
android:layout_above="#+id/messageInputView"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:paddingStart="12dp"
android:paddingEnd="12dp"
android:id="#+id/messageInputView">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:paddingStart="12dp"
android:paddingEnd="12dp"
android:background="#D9D9D9"
android:id="#+id/border"
android:layout_alignParentTop="true"/>
<EditText
android:id="#+id/messageInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="#color/transparent"
android:layout_toLeftOf="#+id/messageSendButton"
android:hint="Type a message..."
android:textColorHint="#80282a2b"
android:inputType="textAutoCorrect|textAutoComplete|textMultiLine|textCapSentences"/>
<ImageView
android:id="#+id/messageSendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:src="#drawable/ic_send"
android:onClick="onClick"
android:padding="4dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:background="#drawable/send_message_background"/>
</RelativeLayout>
</RelativeLayout>
All callback methods of RecyclerView.Adapter<RecyclerView.ViewHolder> not calling on calling notifydatasetchanged().
Adapter code here :
public class ChatMessagesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static String TAG = "ChatMessagesAdapter";
private ArrayList<ChatMessages> mChatMessages;
private Context mContext;
public ChatMessagesAdapter(ArrayList<ChatMessages> chatMessages, Context context){
mContext = context.getApplicationContext();
mChatMessages = chatMessages;
Log.d("ChatActivity Adapter", String.valueOf(mChatMessages.size()));
setHasStableIds(true);
}
public synchronized void refreshData(ArrayList<ChatMessages> feeds){
Log.d("ChatActivity Adapter", String.valueOf(feeds.size()));
mChatMessages.clear();
mChatMessages.addAll(feeds);
Log.d("ChatActivity Adapter", String.valueOf(mChatMessages.size()));
notifyDataSetChanged();
}
class IncomingMessageHolder extends RecyclerView.ViewHolder {
#BindView(R.id.messageText) TextView mMessageText;
#BindView(R.id.messageTime) TextView mMessageTime;
IncomingMessageHolder(View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
}
class OutgoingMessageHolder extends RecyclerView.ViewHolder {
#BindView(R.id.messageText) TextView mMessageText;
#BindView(R.id.messageTime) TextView mMessageTime;
OutgoingMessageHolder(View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
}
#Override
public int getItemViewType(int position) {
Log.d("ChatActivity Adapter","getItemViewType "+mChatMessages.get(position).getMessageStatus());
if (mChatMessages.get(position).getMessageStatus() == 2){
return 1;
} else {
return 0;
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d("ChatActivity Adapter","onCreateViewHolder");
switch (viewType){
case 0 :
View outgoingMessageView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_outcoming_text_message,parent,false);
return new OutgoingMessageHolder(outgoingMessageView);
default :
View incomingMessageView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_incoming_text_message, parent, false);
return new IncomingMessageHolder(incomingMessageView);
}
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
Log.d("ChatActivity Adapter","onBindViewHolder");
switch (holder.getItemViewType()){
case 0:
OutgoingMessageHolder outgoingMessageHolder = (OutgoingMessageHolder) holder;
outgoingMessageHolder.mMessageText.setText(mChatMessages.get(position).getMessage());
outgoingMessageHolder.mMessageTime.setText(
UtilsFuntions.getDurationString(mChatMessages.get(position).getTimeStamp())
);
break;
case 1:
IncomingMessageHolder incomingMessageHolder = (IncomingMessageHolder) holder;
incomingMessageHolder.mMessageText.setText(mChatMessages.get(position).getMessage());
incomingMessageHolder.mMessageTime.setText(
UtilsFuntions.getDurationString(mChatMessages.get(position).getTimeStamp())
);
break;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
Log.d("ChatActivity Adapter", String.valueOf(mChatMessages.size()));
return mChatMessages.size();
}
}
Code for initalizing recyclerView:
mLayoutManager = new LinearLayoutManager(getApplicationContext());
mLayoutManager.setItemPrefetchEnabled(true);
mChatMessages.setItemViewCacheSize(0);
mChatMessages.setDrawingCacheEnabled(true);
mChatMessages.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
mChatMessages.setLayoutManager(mLayoutManager);
mChatMessages.setHasFixedSize(true);
mChatMessagesAdapter = new ChatMessagesAdapter(mChatItems,
getApplicationContext());
mChatMessages.addOnScrollListener(listerOnScroll);
mChatMessages.setAdapter(mChatMessagesAdapter);
ChatMessages chatMessage = new ChatMessages();
chatMessage.setMessage(mChatMessage.getText().toString().trim());
chatMessage.setMessageStatus(2);
chatMessage.setTimeStamp(System.currentTimeMillis());
mChatItems.add(chatMessage);
mChatMessagesAdapter.refreshData(mChatItems);
But when even I touch recyclerview or try to scroll recyclerview all callbacks called and recyclerview get populated. I don't know why this is happening. Please help me to solve this
Related
I have a recycler inside fragment in view pager.
The problem that it put likes on user accounts in UI randomly but in DB everything is fine.
In logs, I see that random is not influence on BD. So the bug is only in UI part. After the refresh of the list, it can appear again and after that disappear.
I would like to share code but I already don't have an I idea where the problem could be. It might be in adapter/refresh list listener / XML or any other places. Please let me know what part of the code you need and I will provide it. Maybe it is a bug of recycler as itself and I can't fix it.
Adapter class code:
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.UserViewHolder>{
private List<FsUser> fsUserList = new ArrayList<>();
private OnItemClickListener.OnItemClickCallback onItemClickCallback;
private OnItemClickListener.OnItemClickCallback onChatClickCallback;
private OnItemClickListener.OnItemClickCallback onLikeClickCallback;
private Context context;
public SearchAdapter(OnItemClickListener.OnItemClickCallback onItemClickCallback,
OnItemClickListener.OnItemClickCallback onChatClickCallback,
OnItemClickListener.OnItemClickCallback onLikeClickCallback) {
this.onItemClickCallback = onItemClickCallback;
this.onChatClickCallback = onChatClickCallback;
this.onLikeClickCallback = onLikeClickCallback;
}
public void addUsers(List<FsUser> userList) {
fsUserList.addAll(userList);
notifyItemRangeInserted(fsUserList.size() - userList.size(), fsUserList.size());
}
public void clearData(){
fsUserList.clear();
notifyDataSetChanged();
}
#NonNull
#Override
public UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user, parent, false);
return new UserViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull UserViewHolder holder, int position) {
FsUser fsUser = fsUserList.get(position);
holder.bind(fsUser, position);
}
#Override
public int getItemCount() {
return fsUserList.size();
}
public String getLastItemId(){
return fsUserList.get(fsUserList.size() - 1).getUid();
}
class UserViewHolder extends RecyclerView.ViewHolder {
RelativeLayout container;
ImageView imageView, like, chat;
TextView name, country;
private LottieAnimationView animationView;
UserViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
container = itemView.findViewById(R.id.item_user_container);
imageView = itemView.findViewById(R.id.user_img);
like = itemView.findViewById(R.id.search_btn_like);
chat = itemView.findViewById(R.id.search_btn_chat);
name = itemView.findViewById(R.id.user_name);
country = itemView.findViewById(R.id.user_country);
animationView = itemView.findViewById(R.id.lottieAnimationView);
}
void bind(FsUser fsUser, int position){
ViewCompat.setTransitionName(imageView, fsUser.getName());
if (FirebaseUtils.isUserExist() && fsUser.getUid() != null) {
new FriendRepository().isLiked(fsUser.getUid(), flag -> {
if (flag) {
like.setBackground(ContextCompat.getDrawable(context, R.drawable.ic_favorite));
animationView.setVisibility(View.VISIBLE);
}
});
}
if(fsUser.getUid() != null) {
chat.setOnClickListener(new OnItemClickListener(position, onChatClickCallback));
like.setOnClickListener(new OnItemClickListener(position, onLikeClickCallback));
}
imageView.setOnClickListener(new OnItemClickListener(position, onItemClickCallback));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
if(fsUser.getImage().equals("default")){
Glide.with(context).load(context.getResources().getDrawable(R.drawable.default_avatar)).into(imageView);
} else {
Glide.with(context).load(fsUser.getImage()).thumbnail(0.5f).into(imageView);
}
name.setText(fsUser.getName());
country.setText(fsUser.getCountry());
ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f).setDuration(500);
animator.addUpdateListener(valueAnimator ->
animationView.setProgress((Float) valueAnimator.getAnimatedValue()));
if (animationView.getProgress() == 0f) {
animator.start();
} else {
animationView.setProgress(0f);
}
}
}
}
And xml file of RecyclerView item:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/item_user_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="#dimen/user_cv_width"
android:layout_height="#dimen/user_cv_height"
android:layout_margin="#dimen/dp4"
android:elevation="#dimen/dp4">
<RelativeLayout
android:id="#+id/item_user_main_relative_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/item_user_top_relative_container"
android:layout_width="#dimen/user_rl_width"
android:layout_height="#dimen/user_rl_height">
<ImageView
android:id="#+id/user_img"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerCrop"
android:src="#drawable/default_avatar" />
<RelativeLayout
android:id="#+id/item_user_top_relative"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/user_item_bg"
android:orientation="vertical">
<TextView
android:id="#+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/dp4"
android:textColor="#android:color/white"
android:textSize="#dimen/medium_text_size" />
<TextView
android:id="#+id/user_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:layout_marginStart="#dimen/dp4"
android:textSize="#dimen/medium_text_size" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/item_user_bottom_relative_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/dp12">
<ImageView
android:id="#+id/search_btn_like"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/heart_outline"
android:contentDescription="#string/search_btn_like_desc"/>
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/lottieAnimationView"
android:visibility="gone"
android:layout_width="#dimen/lottie_animation_view_size"
android:layout_height="#dimen/lottie_animation_view_size"
app:lottie_loop="true"
app:lottie_autoPlay="true"
app:lottie_fileName="like.json"/>
</RelativeLayout>
<ImageView
android:id="#+id/search_btn_chat"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/dp12"
android:layout_weight="1"
android:src="#drawable/message_outline" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
Override this two methods inside your adapter
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
My RecyclerView's item layout has a ViewPager on top and some views below it. ViewPager works fine, swipes good. But the recycler item click is not working on clicking the ViewPager (I've set click on the entire item). But if I click the content below the ViewPager, Click works.
here's the RecyclerView's list item
<?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:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:orientation="horizontal"
xmlns:attrs="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#android:color/white"
card_view:cardCornerRadius="8dp"
card_view:cardElevation="6dp"
card_view:cardUseCompatPadding="true"
android:layout_marginTop="8dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="0dp" android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintDimensionRatio="H,4:2"/>
<com.rd.PageIndicatorView
android:id="#+id/pageIndicatorView"
android:layout_width="wrap_content"
android:layout_height="20dp"
app:piv_animationType="scale"
app:piv_dynamicCount="true"
app:piv_interactiveAnimation="true"
app:piv_selectedColor="#color/whiteSmoke"
app:piv_unselectedColor="#color/white25Transparent"
app:piv_viewPager="#id/viewPager"
attrs:piv_padding="2dp"
attrs:piv_radius="4dp"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="#id/viewpager" android:layout_marginBottom="0dp"/>
<com.codeairs.wattamatte.customcontrols.textview.MPRegularTextView
android:id="#+id/name"
android:layout_width="0dp" android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/viewpager" android:layout_marginTop="6dp"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"
android:layout_marginStart="12dp" android:layout_marginLeft="12dp"
android:layout_marginEnd="12dp" android:layout_marginRight="12dp"
android:text="Cosy Duplex - 42m2" android:textColor="#color/stPatricksBlue"/>
<com.codeairs.wattamatte.customcontrols.textview.MPMediumTextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/RoomDimensTextView"
app:layout_constraintTop_toBottomOf="#id/name" android:layout_marginTop="6dp"
app:layout_constraintStart_toStartOf="#id/name"
android:text="3p"/>
<com.codeairs.wattamatte.customcontrols.textview.MPMediumTextView
android:id="#+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/RoomDimensTextView"
app:layout_constraintTop_toBottomOf="#id/name" android:layout_marginTop="6dp"
app:layout_constraintStart_toEndOf="#id/tv1"
android:layout_marginStart="12dp" android:layout_marginLeft="12dp"
android:text="2ch"/>
<com.codeairs.wattamatte.customcontrols.textview.MPMediumTextView
android:id="#+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/RoomDimensTextView"
app:layout_constraintTop_toBottomOf="#id/name" android:layout_marginTop="6dp"
app:layout_constraintStart_toEndOf="#id/tv2"
android:layout_marginStart="12dp" android:layout_marginLeft="12dp"
android:text="4m"/>
<com.codeairs.wattamatte.customcontrols.textview.MPRegularTextView
android:id="#+id/location"
android:layout_width="0dp" android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/tv1" android:layout_marginTop="6dp"
app:layout_constraintStart_toStartOf="#id/tv1" app:layout_constraintEnd_toEndOf="parent"
android:text="Villeurbanne" android:textColor="#color/darkSlateBlue"
app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="4dp"/>
<com.codeairs.wattamatte.customcontrols.textview.MPBoldTextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="12dp"
android:layout_marginRight="12dp"
app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="12dp"
android:text="450€ C.C" android:textColor="#color/stPatricksBlue" android:textSize="17sp"/>
<View
android:id="#+id/toggleBG"
android:layout_width="36dp" android:layout_height="36dp"
android:background="#drawable/solid_white_circle"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp" android:layout_marginRight="8dp"
app:layout_constraintTop_toBottomOf="#id/viewpager"
app:layout_constraintBottom_toBottomOf="#id/viewpager"/>
<ToggleButton
android:id="#+id/favoritesToggleButton"
android:layout_width="24dp"
android:layout_height="24dp"
android:background="#drawable/bg_fav_toggle"
android:textOn=""
android:textOff=""
app:layout_constraintTop_toTopOf="#id/toggleBG"
app:layout_constraintBottom_toBottomOf="#id/toggleBG"
app:layout_constraintStart_toStartOf="#id/toggleBG"
app:layout_constraintEnd_toEndOf="#id/toggleBG"/>
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
RecylerView Adapter
public class RoomsListRecyclerViewAdapter extends RecyclerView.Adapter<RoomsListRecyclerViewAdapter.ViewHolder> {
private final List<Room> mValues;
private final List<String> favRoomsIds;
private final OnListFragmentInteractionListener mListener;
private final Context mContext;
public RoomsListRecyclerViewAdapter(List<Room> items, List<String> favRoomsIds,
OnListFragmentInteractionListener listener, Context mContext) {
mValues = items;
mListener = listener;
this.favRoomsIds = favRoomsIds;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_rooms_list_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.imgPager.setAdapter(new ImageAdapter(mContext, holder.mItem.property.pictures));
holder.pageIndicatorView.setCount(holder.mItem.property.pictures.size());
holder.pageIndicatorView.setSelection(0);
holder.imgPager.addOnPageChangeListener(getPageChangeListener(holder));
holder.name.setText(holder.mItem.property.name);
holder.location.setText(holder.mItem.property.address.city);
holder.price.setText(MessageFormat.format("{0} € C.C", holder.mItem.property.price));
holder.tv1.setText(MessageFormat.format("{0}p", holder.mItem.property.personCount));
holder.tv2.setText(MessageFormat.format("{0}ch", holder.mItem.property.pieces));
holder.tv3.setText(MessageFormat.format("{0}m²", holder.mItem.property.surface));
holder.favToggle.setChecked(favRoomsIds.contains(holder.mItem.property.id));
holder.favToggle.setOnCheckedChangeListener((buttonView, isChecked) ->
toggleFavorite(holder.mItem.property.id, isChecked));
holder.mView.setOnClickListener(v -> {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem, favRoomsIds.contains(holder.mItem.property.id));
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
final View mView;
Room mItem;
ViewPager imgPager;
TextView name, location, price, tv1, tv2, tv3;
ToggleButton favToggle;
PageIndicatorView pageIndicatorView;
ViewHolder(View view) {
super(view);
mView = view;
imgPager = view.findViewById(R.id.viewpager);
name = view.findViewById(R.id.name);
location = view.findViewById(R.id.location);
price = view.findViewById(R.id.price);
tv1 = view.findViewById(R.id.tv1);
tv2 = view.findViewById(R.id.tv2);
tv3 = view.findViewById(R.id.tv3);
favToggle = view.findViewById(R.id.favoritesToggleButton);
pageIndicatorView = view.findViewById(R.id.pageIndicatorView);
}
#Override
public String toString() {
return super.toString() + " '" + "'";
}
}
private void toggleFavorite(String propertyId, boolean fav) {
if (fav)
favRoomsIds.add(propertyId);
else
favRoomsIds.remove(propertyId);
JsonObjectRequest request = NetworkUtils.toggleRoomFavoritesRequest(
mContext, propertyId, fav, this::handleResponse, this::handleError);
VolleySingleton.getInstance(mContext).addToRequestQueue(request);
}
private void handleResponse(JSONObject response) {
Log.d("RoomFav.Response", response.toString());
}
private void handleError(VolleyError error) {
}
public void clear() {
mValues.clear();
notifyDataSetChanged();
}
public void addItems(List<Room> rooms) {
mValues.addAll(rooms);
notifyDataSetChanged();
}
private ViewPager.OnPageChangeListener getPageChangeListener(ViewHolder holder) {
return new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
holder.pageIndicatorView.setSelected(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
}
pager adapter
public class ImageAdapter extends PagerAdapter {
private Context mContext;
private List<String> mItems;
public ImageAdapter(Context context, List<String> items) {
mContext = context;
mItems = items;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup collection, int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ImageView img = (ImageView) inflater.inflate(R.layout.layout_image, collection, false);
String url = mItems.get(position);
if (!TextUtils.isEmpty(url))
Picasso.get().load(ApiPaths.IMG_PATH_PREFIX + url).into(img);
collection.addView(img);
return img;
}
#Override
public void destroyItem(#NonNull ViewGroup collection, int position, #NonNull Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
}
pager item
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/img"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:scaleType="fitXY"
android:clickable="false"/>
I have recyclerview with cardview to load data and there are two columns, the code work fine but I need to hide the first column with switch widget. I have trying some code but none work for me. Can someone help me. I'm new in android. Thanks
Here is the screenshot
Below is my code
MyFragment.java
public class MyFragment extends Fragment {
public MyFragment() {
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup viewGroup,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recyclerview, viewGroup, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mobile = getResources().getStringArray(R.array.mobile);
desktop = getResources().getStringArray(R.array.desktop);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
MyAdapter adapter = new MyAdapter(getContext());
recyclerView.setAdapter(adapter);
// this code below didn't work. i thought it's because different
// layout between fragment and adapter but i don't know to solve it
final TextView tvMobile = (TextView) view.findViewById(R.id.tv_mobile);
Switch mSwitch = (Switch) view.findViewById(R.id.switch_item);
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
tvMobile.setVisibility(View.GONE);
} else {
tvMobile.setVisibility(View.VISIBLE);
}
}
});
}
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private LayoutInflater inflater;
public static String[] mobile;
public static String[] desktop;
public MyAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
#NonNull
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.item_cardview, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder holder, int position) {
holder.tvMobile.setText(mobile[position]);
holder.tvDesktop.setText(desktop[position]);
}
#Override
public int getItemCount() {
return mobile.length;
}
class MyViewHolder extends RecyclerView.ViewHolder {
private TextView tvMobile;
private TextView tvDesktop;
MyViewHolder(View itemView) {
super(itemView);
tvMobile = (TextView) itemView.findViewById(R.id.tv_mobile);
tvDesktop = (TextView) itemView.findViewById(R.id.tv_desktop);
}
}
}
fragment_recyclerview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_light"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:background="#dfe7f2"
android:gravity="end"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingRight="16dp"
android:paddingTop="5dp">
<Switch
android:id="#+id/switch_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Hide Mobile Row"
android:textColor="#color/text_color"
android:textSize="18sp" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/color_divider" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingBottom="16dp"
android:paddingTop="16dp" />
</LinearLayout>
item_cardview.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginBottom="8dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
card_view:cardBackgroundColor="#color/background_dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:layout_width="5dp"
android:layout_height="match_parent"
android:background="#drawable/bg_card_view" />
<TextView
android:id="#+id/tv_mobile"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:paddingLeft="10dp"
android:text="romaji"
android:textColor="#color/black_1"
android:textSize="16sp" />
<TextView
android:id="#+id/tv_desktop"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:paddingLeft="10dp"
android:text="arti"
android:textColor="#color/black_1"
android:textSize="16sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
In your adapter change like this
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
public static boolean isMobileHided = false; //add this flag
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder holder, int position) {
holder.tvMobile.setText(mobile[position]);
holder.tvDesktop.setText(desktop[position]);
if (isMobileHided) {
holder.tvMobile.setVisblity(View.GONE);
}
else{
holder.tvMobile.setVisblity(View.VISIBLE);
}
}
}
In your switch listener(From activity/fragments)
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//update the switch button status to adapter flag variable
adapter.isMobileHided = isChecked;
//refresh the adapter
adapter.notifyDataSetChanged();
}
});
I am getting a Json output from the server.
This is my Json look like
{
"feed": [
{
"order_no": "70000004",
"quotation_no": "abc004a"
},
{
"order_no": "70000003",
"quotation_no": "abc003a"
},
{
"order_no": "70000001",
"quotation_no": "abc001a"
},
{
"order_no": "70000001",
"quotation_no": "abc001b"
}
]
}
I know how to populate this in a recyclerview. But what I want is grouping this json using order_no and populate. For example there are two 70000001. So i only need to show one 70000001 order no.
This is my custom row .xml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/white">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="2dp"
android:layout_marginLeft="3dp"
android:layout_marginRight="3dp"
android:layout_marginTop="2dp"
android:background="#color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dbdbda"
android:orientation="vertical">
<TextView
android:id="#+id/parent_list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:text="Parent Title"
android:textColor="#color/primaryColorText"
android:textStyle="bold" />
<TextView
android:id="#+id/parent_q_item_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="2dp"
android:text="Q Title"
android:textColor="#color/secondaryColorText"
android:textSize="12sp" />
<TextView
android:id="#+id/parent_q_item_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="2dp"
android:text="Q Title"
android:textColor="#color/secondaryColorText"
android:textSize="12sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
After grouping, I need to show only one order_no in parent_list_item (70000001) and under that I need to show one quotation_no in the first text view and second quotation_no in the second text view under same order_no
My adapter class
public class OrderQuatationHistory extends RecyclerView.Adapter<OrderQuatationHistory.ItemViewHolder> {
private LayoutInflater layoutInflater;
private ArrayList<OrderHistoryData> orderHistoryDataArrayList;
public OrderQuatationHistory() {
}
public OrderQuatationHistory(Context context) {
orderHistoryDataArrayList = new ArrayList<>();
layoutInflater = LayoutInflater.from(context);
}
public void setOrderHistoryList(ArrayList<OrderHistoryData> orderHistoryDataArrayList) {
this.orderHistoryDataArrayList = orderHistoryDataArrayList;
notifyItemRangeChanged(0, orderHistoryDataArrayList.size());
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_order_history_p_row, parent, false);
ItemViewHolder itemViewHolder = new ItemViewHolder(view);
return itemViewHolder;
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
OrderHistoryData orderHistoryData = orderHistoryDataArrayList.get(position);
holder.orderNo.setText(orderHistoryData.getOrderNo());
holder.quotationNo.setText(orderHistoryData.getQuotationNo());
}
#Override
public int getItemCount() {
return orderHistoryDataArrayList.size();
}
public static class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView orderNo,quotationNo;
public ItemViewHolder(View itemView) {
super(itemView);
orderNo = (TextView) itemView.findViewById(R.id.parent_list_item);
quotationNo = (TextView) itemView.findViewById(R.id.parent_q_list);
}
}
}
Try this... For avoiding of duplicate value,you can use this Method.
ArrayList<Integer> jSonOrder=new ArrayList();
int order_no= assigned values that you have retrieved from JSon.
if (!jSonOrder.contains(order_no)) {
jSonOrder.add(order_no);
}
I am using cardview with recycler view.But earlier I used the same code to do things without any problems.But now I am using fragments. Now I am getting the distance between the cardviews are greater.
my recycler view adapter
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView label;
TextView dateTime;
ImageView imageView;
ProgressBar progressBar;
public DataObjectHolder(final View itemView, final Context activity, final ArrayList<DataObject> myDataset) {
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView);
//dateTime = (TextView) itemView.findViewById(R.id.thot);
imageView=(ImageView)itemView.findViewById(R.id.iproductimg);
progressBar=(ProgressBar)itemView.findViewById(R.id.progress);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListenerhi.onItemClick(getLayoutPosition(),v);
}
}
public MyRecyclerViewAdapter(Activity context, ArrayList<DataObject> myDataset,MyClickListener myClickListener1) {
mDataset = myDataset;
activityContext=context;
myClickListenerhi=myClickListener1;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view,activityContext,mDataset);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(final DataObjectHolder holder, int position) {
Context context=null;
holder.label.setText(mDataset.get(position).getmText1());
// holder.dateTime.setText(mDataset.get(position).getmText2());
Drawable placeholder = holder.imageView.getContext().getResources().getDrawable(R.drawable.placeholder);
holder.imageView.setImageDrawable(placeholder);
//new ImageDownloaderTask(holder.imageView).execute(mDataset.get(position).getUrl());
mDataset.get(position).setPosition(position);
Picasso.with(activityContext)
.load(mDataset.get(position).getUrl())
.placeholder(R.drawable.placeholder)
.into(holder.imageView, new Callback() {
#Override
public void onSuccess() {
holder.progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onError() {
}
});
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
void onItemClick(int position, View v);
}
}
my cardview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="3"
>
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="156dp"
android:layout_height="242dp"
android:layout_margin="5dp"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="5dp"
card_view:cardBackgroundColor="#ffffff">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:id="#+id/iproductimg"
android:src="#drawable/placeholder"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:scaleType="fitXY" />
<ProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
android:indeterminate="false" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/firstheadtxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
The error
I solved this by changing Cardview LinearLayout attribute from
android:layout_width="match_parent"
android:layout_height="match_parent"
to
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Edit:
Main problem is that the recyclerviews child layout or item layout rootview attribute is match_parent.
change it attribut to wrap_content
android:layout_width="wrap_content"
android:layout_height="wrap_content"
In this case : in the layout of cardview:
remove :layout_margin="5dp"
add :
margin_top = "3dp"
margin_left = "5dp"
margin_right = "5dp"