How to change text of child view onclick of recycler view? - android

I have it clicked and it gets up to it and shows the right getText() method but the setText method is not working...
userAdapter.setOnEntryClickListener(new UserAdapter.OnEntryClickListener() {
#Override
public void onEntryClick(View view, int position) {
DatabaseUser user = dbUsersList.get(position);
TextView clickedView = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
if(view == clickedView) {
if (clickedView.getText().equals("following")) {
Log.d(Constants.DEBUG, " THE CLICK VIEW IS " + clickedView.getText());
//APPLY Following
String txtFollow = "follow";
clickedView.setText(txtFollow);
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(3);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
} else {
clickedView.setText("following");
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(0);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(getApplicationContext(), user.getUsername() + " is selected!", Toast.LENGTH_SHORT).show();
takeToUserProfile(dbUsersList.get(position));
}
}
});
Here is the adapter class:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.MyViewHolder> {
private List<DatabaseUser> dbUsersList, followingList;
private DatabaseHelper db;
private Context context;
private Typeface typeFace, italicTypeface, boldTypeface;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView userAdapterUsername, userAdapterFollowBtn;
public ImageView userAdapterUserPicture;
public MyViewHolder(View view) {
super(view);
userAdapterUsername = (TextView) view.findViewById(R.id.userAdapterUsername);
userAdapterFollowBtn = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
userAdapterUserPicture = (ImageView) view.findViewById(R.id.userAdapterUserPicture);
Log.d(Constants.DEBUG, "IN MY VIEW HOLDER");
view.setOnClickListener(this);
userAdapterFollowBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mOnEntryClickListener != null) {
Log.d(Constants.DEBUG, "IN On click");
mOnEntryClickListener.onEntryClick(v, getAdapterPosition());
}
}
}
private static OnEntryClickListener mOnEntryClickListener;
public interface OnEntryClickListener {
void onEntryClick(View view, int position);
}
public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {
mOnEntryClickListener = onEntryClickListener;
}
public UserAdapter(Context mContext, List<DatabaseUser> usersList, List<DatabaseUser> passedFollowing, Typeface myTypeface, Typeface myTypefaceItalic, Typeface myTypefaceBold) {
context = mContext;
dbUsersList = usersList;
followingList = passedFollowing;
typeFace = myTypeface;
italicTypeface = myTypefaceItalic;
boldTypeface = myTypefaceBold;
Log.d(Constants.DEBUG, "IN MY User ADAPTER CONSTRUCTOR");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.follow_item, parent, false);
Log.d(Constants.DEBUG, "RETURN ITEM VIEW HOLDER");
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
DatabaseUser user = dbUsersList.get(position);
holder.userAdapterUsername.setTypeface(boldTypeface);
holder.userAdapterUsername.setText(user.getUsername());
final int pos = getItemViewType(position);
//TODO Create pic link
if(containsId(dbUsersList.get(pos), followingList)) {
//Then show following
holder.userAdapterFollowBtn.setText("following");
} else {
//show follow
holder.userAdapterFollowBtn.setText("follow");
}
String userspic = dbUsersList.get(pos).getPicture();
if(userspic == null) {
//SET DEFAULT OR PUT DEFAULT IN XML AND DO NOTHING IT SHOULD SHOW DEFAULT PIC
} else {
//TODO setupUser Pic
String img1 = "http://www.hindustantimes.com/Images/popup/2015/6/kungfu2.jpg";
Picasso.with(context).load(img1).transform(new RoundedTransformation()).into(holder.userAdapterUserPicture);
}
}
#Override
public int getItemCount() {
return dbUsersList.size();
}
public static boolean containsId(DatabaseUser currentUser, List<DatabaseUser> list) {
for (DatabaseUser object : list) {
if (currentUser.getUserId().equals(object.getUserId())) {
return true;
}
}
return false;
}
#Override
public int getItemViewType(int position) {
return position;
}
}

your dbUsersList is not updating. please check your user object in dbUsersList after notify data set change.

What ended up being the problem is that I had passed in the followingList, so I never re-called to grab the new following from the db on update. The update was happening I just had to re-grab the followingList from the db to have an updated list to check against like so in a new method that was passing the list back to the contains method.
db.grabFollowersList();

Related

recyclerView whit multi view type get messed up on scrolling

i have a recyclerView which contains three type of view ; in the view type 2 i am checking if the file exits on the internal storage so i load it from storage and if
it is not i show a small image view in center of view to download it . when user click download image view the image changes from download icon to pause icon but this happen for some other rows ...
the mainly accepted answers to this question are
holder.setIsRecyclable(false);
but this ruin the purpose of recyclerView
2.override this methods
#Override public long getItemId(int position) {
return position; }
#Override public int getItemViewType(int position) {
return position; }
and my code
#Override
public int getItemViewType(int position) {
int type = messages.get(position).getType();
if (type==1) {
return 1;
}else if (type==2) {
return 2 ;
}else if (type==3) {
return 3;
}
else {
return -1;
}
}
#Override
public long getItemId(int position) {
return position;
}
setHasStableIds(true);
not Working
4.write both if and else conditions in onBindViewHolder
switch (holder.getItemViewType()) {
case 1 :
SimpleHolder simpleHolder = (SimpleHolder)holder;
simpleHolder.tv_text.setText(message.getMessage());
simpleHolder.tv_time.setText(time);
if (message.getLiked()==0) {
simpleHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.unlike));
}else {
simpleHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.like));
}
break;
case 2 :
ImageHolder imageHolder = (ImageHolder)holder;
//in method esme folder va esme aks ro migire o check mikone bebine mojode ya na
if (isFileExists(Config.Folders.IMAGES ,message.getUrl())) {
imageHolder.circularProgressBar.setVisibility(View.GONE);
imageHolder.iv_download.setVisibility(View.GONE);
Glide.with(context).load(getFile(Config.Folders.IMAGES,message.getUrl())).apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
) .into(new SimpleTarget<Drawable>() {
#Override
public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
((ImageHolder) holder).iv_picture.setImageDrawable(resource);
}
});
imageHolder.iv_picture.setImageURI(Uri.fromFile(getFile(Config.Folders.IMAGES,message.getUrl())));
}else {
imageHolder.iv_download.setVisibility(View.VISIBLE);
imageHolder.circularProgressBar.setVisibility(View.VISIBLE);
Glide.with(context).load(Config.MESSAGE_THUMB_ADDRESS+message.getThumb()).apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(ContextCompat.getDrawable(context,R.drawable.white))
).into(imageHolder.iv_picture);
}
imageHolder.tv_time.setText(time);
if (message.getMessage()!=null) {
imageHolder.tv_text.setVisibility(View.VISIBLE);
imageHolder.tv_text.setText(message.getMessage());
}else {
imageHolder.tv_text.setVisibility(View.GONE);
}
if (message.getLiked()==0) {
imageHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.unlike));
}else {
imageHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.like));
}
break;
but still none of them works
the whole code of my adapter class is
public class Message_Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
ArrayList<Message> messages;
ClickListener clickListener;
public Message_Adapter(Context context, ArrayList<Message> messages) {
this.context = context;
this.messages = messages;
setHasStableIds(true);
}
public interface ClickListener {
public void picture_imageClicked(int position, View view, CircularProgressBar circularProgressBar, ImageView iv_download);
public void picture_likeClicked(int position, View view);
public void picture_commentClicked(int position, View view);
public void simple_likeClicked(int position, View view);
public void simple_commentClicked(int position, View view);
public void video_imageClicked(int position, View view, CircularProgressBar circularProgressBar, ImageView iv_download);
public void video_likeClicked(int position, View view);
public void video_commentClicked(int position, View view);
}
public void setCliclListener(ClickListener cliclListener) {
this.clickListener = cliclListener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 1) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_simple, parent, false);
return new SimpleHolder(view);
} else if (viewType == 2) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_picture, parent, false);
CircularProgressBar circularProgressBar = (CircularProgressBar) view.findViewById(R.id.cp_picturee);
circularProgressBar.setColor(ContextCompat.getColor(context, android.R.color.holo_blue_dark));
circularProgressBar.setBackgroundColor(ContextCompat.getColor(context, android.R.color.holo_blue_dark));
circularProgressBar.setProgressBarWidth(10);
circularProgressBar.setBackgroundProgressBarWidth(5);
int animationDuration = 2500; // 2500ms = 2,5s
// circularProgressBar.setProgressWithAnimation(65, animationDuration);
return new ImageHolder(view);
} else if (viewType == 3) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_video, parent, false);
CircularProgressBar circularProgressBar = (CircularProgressBar) view.findViewById(R.id.cp_video);
circularProgressBar.setColor(ContextCompat.getColor(context, android.R.color.holo_blue_dark));
circularProgressBar.setBackgroundColor(ContextCompat.getColor(context, android.R.color.holo_blue_dark));
circularProgressBar.setProgressBarWidth(10);
circularProgressBar.setBackgroundProgressBarWidth(5);
return new VideoHolder(view);
} else {
throw new RuntimeException("The type has to be ONE or TWO");
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
Message message = messages.get(position);
String time = "00:00";
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(message.getUpdated_at());
time = new SimpleDateFormat("H:mm").format(date);
} catch (ParseException e) {
e.printStackTrace();
}
switch (holder.getItemViewType()) {
case 1:
SimpleHolder simpleHolder = (SimpleHolder) holder;
simpleHolder.tv_text.setText(message.getMessage());
simpleHolder.tv_time.setText(time);
if (message.getLiked() == 0) {
simpleHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.unlike));
} else {
simpleHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.like));
}
break;
case 2:
ImageHolder imageHolder = (ImageHolder) holder;
//in method esme folder va esme aks ro migire o check mikone bebine mojode ya na
if (isFileExists(Config.Folders.IMAGES, message.getUrl())) {
imageHolder.circularProgressBar.setVisibility(View.GONE);
imageHolder.iv_download.setVisibility(View.GONE);
Glide.with(context).load(getFile(Config.Folders.IMAGES, message.getUrl())).apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
).into(new SimpleTarget<Drawable>() {
#Override
public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
((ImageHolder) holder).iv_picture.setImageDrawable(resource);
}
});
imageHolder.iv_picture.setImageURI(Uri.fromFile(getFile(Config.Folders.IMAGES, message.getUrl())));
} else {
imageHolder.iv_download.setVisibility(View.VISIBLE);
imageHolder.circularProgressBar.setVisibility(View.VISIBLE);
Glide.with(context).load(Config.MESSAGE_THUMB_ADDRESS + message.getThumb()).apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(ContextCompat.getDrawable(context, R.drawable.white))
).into(imageHolder.iv_picture);
}
imageHolder.tv_time.setText(time);
if (message.getMessage() != null) {
imageHolder.tv_text.setVisibility(View.VISIBLE);
imageHolder.tv_text.setText(message.getMessage());
} else {
imageHolder.tv_text.setVisibility(View.GONE);
}
if (message.getLiked() == 0) {
imageHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.unlike));
} else {
imageHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.like));
}
break;
case 3:
VideoHolder videoHolder = (VideoHolder) holder;
videoHolder.tv_time.setText(time);
if (message.getMessage() != null) {
videoHolder.tv_text.setVisibility(View.VISIBLE);
videoHolder.tv_text.setText(message.getMessage());
} else {
videoHolder.tv_text.setVisibility(View.GONE);
}
if (message.getLiked() == 0) {
videoHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.unlike));
} else {
videoHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.like));
}
Glide.with(context).load(Config.VIDEO_PIC_ADDRES + message.getThumb()).apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
).into(videoHolder.iv_picture);
if (isFileExists(Config.Folders.VIDEOS, message.getUrl())) {
videoHolder.circularProgressBar.setVisibility(View.INVISIBLE);
videoHolder.iv_download.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.play));
} else {
videoHolder.iv_download.setVisibility(View.VISIBLE);
videoHolder.circularProgressBar.setVisibility(View.VISIBLE);
videoHolder.iv_download.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.download));
}
String lenth = message.getLenth() < 1024 ? message.getLenth() + " kb" : message.getLenth() / 1024 + " mb";
videoHolder.tv_video_time.setText(message.getTime() + " | " + lenth);
break;
default:
break;
}
}
public boolean isFileExists(String folderName, String filename) {
if (filename == null) {
filename = "null";
}
File file = new File(Environment.getExternalStorageDirectory() + "/NoorAlSalehin/" + folderName, filename);
return file.exists();
}
public File getFile(String folderName, String filename) {
File file = new File(Environment.getExternalStorageDirectory() + "/NoorAlSalehin/" + folderName, filename);
return file;
}
#Override
public int getItemCount() {
return messages.size();
}
#Override
public int getItemViewType(int position) {
int type = messages.get(position).getType();
if (type == 1) {
return 1;
} else if (type == 2) {
return 2;
} else if (type == 3) {
return 3;
} else {
return -1;
}
}
#Override
public long getItemId(int position) {
return position;
}
class SimpleHolder extends RecyclerView.ViewHolder {
TextView tv_text, tv_time;
ImageView iv_like, iv_comment;
public SimpleHolder(View itemView) {
super(itemView);
tv_text = (TextView) itemView.findViewById(R.id.tv_custom_simple_text);
iv_like = (ImageView) itemView.findViewById(R.id.iv_simple_like);
iv_comment = (ImageView) itemView.findViewById(R.id.iv_simple_comment);
tv_time = (TextView) itemView.findViewById(R.id.tv_simple_time);
iv_like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.simple_likeClicked(getAdapterPosition(), view);
}
});
iv_comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.simple_commentClicked(getAdapterPosition(), view);
}
});
}
}
class ImageHolder extends RecyclerView.ViewHolder {
ImageView iv_picture, iv_download, iv_like, iv_comment;
TextView tv_text, tv_time;
CircularProgressBar circularProgressBar;
public ImageHolder(View itemView) {
super(itemView);
iv_download = (ImageView) itemView.findViewById(R.id.iv_picture_download);
iv_picture = (ImageView) itemView.findViewById(R.id.iv_picture_image);
circularProgressBar = (CircularProgressBar) itemView.findViewById(R.id.cp_picturee);
tv_text = (TextView) itemView.findViewById(R.id.tv_picture_text);
iv_comment = (ImageView) itemView.findViewById(R.id.iv_picture_comment);
tv_time = (TextView) itemView.findViewById(R.id.tv_picture_time);
iv_picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.picture_imageClicked(getAdapterPosition(), view, circularProgressBar, iv_download);
}
});
iv_like = (ImageView) itemView.findViewById(R.id.iv_picture_like);
iv_like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.picture_likeClicked(getAdapterPosition(), view);
}
});
iv_comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.picture_commentClicked(getAdapterPosition(), view);
}
});
}
}
class VideoHolder extends RecyclerView.ViewHolder {
// ImageView iv_picture , iv_like , iv_comment;
ImageView iv_picture, iv_download, iv_like, iv_comment;
TextView tv_text, tv_time, tv_video_time;
// CircleProgressView circleProgressView ;
CircularProgressBar circularProgressBar;
public VideoHolder(View itemView) {
super(itemView);
iv_download = (ImageView) itemView.findViewById(R.id.iv_video_download_playy);
iv_picture = (ImageView) itemView.findViewById(R.id.iv_video_image);
// circleProgressView=(CircleProgressView)itemView.findViewById(R.id.cp_video_download);
circularProgressBar = (CircularProgressBar) itemView.findViewById(R.id.cp_video);
tv_text = (TextView) itemView.findViewById(R.id.tv_video_text);
iv_comment = (ImageView) itemView.findViewById(R.id.iv_video_comment);
tv_time = (TextView) itemView.findViewById(R.id.tv_video_time);
iv_picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.video_imageClicked(getAdapterPosition(), view, circularProgressBar, iv_download);
}
});
tv_video_time = (TextView) itemView.findViewById(R.id.tv_video_video_time);
iv_like = (ImageView) itemView.findViewById(R.id.iv_video_like);
iv_like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.video_likeClicked(getAdapterPosition(), view);
}
});
iv_comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.video_commentClicked(getAdapterPosition(), view);
}
});
}
}
}

scroll recyclerview after click item of another recyclerview?

I want to scroll recyclerview by click on category position of another recyclerview which is called in popup menu...Below is my code, I am using Sectional Recyclerview and i want to get section item position while click on second recyclerview item...Please note that both recyclerview item's category id is same;
CategoryMenuRecyclerview Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<MenuItem.ProductCategory> mDataset;
private ItemListner itemListner;
RestaurantMenuActivity mContext;
public MyAdapter(RestaurantMenuActivity mContext, ArrayList<MenuItem.ProductCategory> productList, ItemListner itemListner) {
mDataset = productList;
this.itemListner = itemListner;
this.mContext = mContext;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mainView;
TextView tvCategory, tvCategoryNo;
public ViewHolder(View v) {
super(v);
mainView = v;
tvCategory = (TextView) v.findViewById(R.id.tvCategory);
tvCategoryNo = (TextView) v.findViewById(R.id.tvCategoryNo);
}
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.tvCategory.setText(mDataset.get(position).getCategoryName());
holder.mainView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemListner.Item(position);
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
and i want to scroll below adapter with click item of upper recyclerview item;
RestaurantMenuAdapter;
public class RestaurantMenuAdapter extends SectionedRecyclerViewAdapter<RecyclerView.ViewHolder> {
private List<MenuItem.ProductCategory> allData;
public RestaurantMenuAdapter(List<MenuItem.ProductCategory> data) {
this.allData = data;
}
#Override
public int getSectionCount() {
return allData == null ? 0 : allData.size();
}
private MenuItem.ProductCategory getItem(int position) {
return allData.get(position);
}
#Override
public int getItemCount(int section) {
return allData.get(section).getProductDetails() == null ? 0 : allData.get(section).getProductDetails().size();
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int section) {
String sectionName = allData.get(section).getCategoryName();
SectionViewHolder sectionViewHolder = (SectionViewHolder) holder;
sectionViewHolder.tvCategory.setText(sectionName);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int section, final int relativePosition, int absolutePosition) {
final ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.tvProductName.setText(allData.get(section).getProductDetails().get(relativePosition).getProductName());
itemViewHolder.tvDescription.setText("Grass Fed Beef with creespy bacon, tasty cheese, salad, relish and hot");
itemViewHolder.tvPrice.setText("$ " + allData.get(section).getProductDetails().get(relativePosition).getCurrentPrice());
if (near_by_restaurant) {
rlAddCart.setVisibility(View.VISIBLE);
if (tvCategoryCount.getText().toString().matches("0")) {
rlAddCart.setVisibility(View.GONE);
} else {
rlAddCart.setVisibility(View.VISIBLE);
}
if (allData.get(section).getProductDetails().get(relativePosition).getIsOpen().equalsIgnoreCase("1")) {
itemViewHolder.ll_product.setAlpha(0.5f);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry kitchen is closed")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
} else if (allData.get(section).getProductDetails().get(relativePosition).getIsSoldout().equalsIgnoreCase("1")) {
itemViewHolder.tvSoldOut.setVisibility(View.VISIBLE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry all items are sold out")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
dialog.dismiss();
}
})
.show();
}
});
} else {
itemViewHolder.tvSoldOut.setVisibility(View.GONE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPref = getSharedPreferences("cartitems", 0);
String strJson = sharedPref.getString("cartdata", "0");
try {
mainjsonArray = new JSONArray(strJson);
} catch (JSONException e) {
e.printStackTrace();
}
Intent i = new Intent(RestaurantMenuActivity.this, ProductCartActivity.class);
i.putExtra("product_id", allData.get(section).getProductDetails().get(relativePosition).getProductID());
i.putExtra("productCart", true);
i.putExtra("product_name", allData.get(section).getProductDetails().get(relativePosition).getProductName());
i.putExtra("product_price", allData.get(section).getProductDetails().get(relativePosition).getCurrentPrice());
try {
i.putExtra("jsonArray", mainjsonArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
startActivityForResult(i, PRODUCT_CART);
}
});
}
} else {
rlAddCart.setVisibility(View.GONE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry you are not in restaurant")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
dialog.dismiss();
}
})
.show();
}
});
}
if (allData.get(section).getProductDetails().get(relativePosition).getFavorited() == 0) {
itemViewHolder.ivFav.setImageResource(R.drawable.fav_02);
} else {
itemViewHolder.ivFav.setImageResource(R.drawable.favroite_highlited);
}
itemViewHolder.ivFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog pd = ProgressDialog.show(RestaurantMenuActivity.this, "", "Loading...");
JSONObject postdata = new JSONObject();
try {
YupITApplication.getJsonWithHTTPPost(RestaurantMenuActivity.this, 1, new ServiceCallBack() {
#Override
public void serviceCallback(int id, JSONObject jsonResult) {
pd.dismiss();
try {
if (jsonResult.has("Data") && !jsonResult.getString("Data").equals("")) {
// {"Status":"Success","StatusCode":"200","Message":"Item Favourited!","Data":[]}
if (jsonResult.getString("Message").equalsIgnoreCase("Item Favourited!")) {
itemViewHolder.ivFav.setImageResource(R.drawable.favroite_highlited);
} else {
itemViewHolder.ivFav.setImageResource(R.drawable.fav_02);
}
Toast.makeText(getApplicationContext(), jsonResult.getString("Message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, Utils.insertfavoriteitem + "&productid=" + allData.get(section).getProductDetails().get(relativePosition).getProductID() + "&userid=" + customer_id, postdata);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Glide.with(RestaurantMenuActivity.this).load(allData.get(section).getProductDetails().get(relativePosition).getPhotoImagePath())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(itemViewHolder.ivMenu);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, boolean header) {
View v = null;
if (header) {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_section, parent, false);
v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
width = v.getMeasuredWidth();
height = v.getMeasuredHeight();
return new SectionViewHolder(v);
} else {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ItemViewHolder(v);
}
}
// SectionViewHolder Class for Sections
public class SectionViewHolder extends RecyclerView.ViewHolder {
final TextView tvCategory;
public SectionViewHolder(View itemView) {
super(itemView);
tvCategory = (TextView) itemView.findViewById(R.id.tvCategory);
}
}
// ItemViewHolder Class for Items in each Section
public class ItemViewHolder extends RecyclerView.ViewHolder {
final TextView tvProductName, tvDescription, tvPrice, tvSoldOut;
LinearLayout ll_product;
ImageView ivMenu, ivFav;
public ItemViewHolder(View itemView) {
super(itemView);
tvProductName = (TextView) itemView.findViewById(R.id.tvProductName);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
ivMenu = (ImageView) itemView.findViewById(R.id.ivMenu);
ll_product = (LinearLayout) itemView.findViewById(R.id.ll_product);
tvSoldOut = (TextView) itemView.findViewById(R.id.tvSoldOut);
ivFav = (ImageView) itemView.findViewById(R.id.ivFav);
}
}
public int isSectionHeaderPosition(int position) {
return Integer.parseInt(allData.get(position).getCategoryID());
}
}
Please help
i think that the position of category in popup menu will be the same as section value of the second recyclerView if you get the position of clicked item in your activity by listening on item's click you can scroll the recyclerView using the LayoutManager.
recyclerView.getLayoutManager().scrollToPosition(youPositionInTheAdapter).

How to refresh the Recyclerview when Image is deleted?

In my app, I want to delete the images, which i have done, but every time I delete image, it doesn't refresh the recyclerView. But when I again open the folder then Recyclerview is refreshed..
I want to refresh Recyclerview when image is deleted
Here is my code for Deleting an image
#Override
protected void onExternalStoragePermissionGranted() {
super.onExternalStoragePermissionGranted();
storage = SimpleStorage.getExternalStorage();
checkForGalleryDirectories();
File galleryFiles = new File(path);
pathContainerView.removeAllViews();
pathContainerView.addView(createTitleView("Location: " + galleryFiles.getAbsolutePath()));
File[] files = galleryFiles.listFiles();
List<GalleryItem> galleryItems = new ArrayList<>();
String lastModifiedDate = "UNDEFINED";
SimpleDateFormat formatter = new SimpleDateFormat("E-MMM-yyyy");
if (files != null) {
this.adapter.clearGallery();
for (File file : files) {
if (file.isDirectory()) {
}
String formattedPicDate = formatter.format(lastMod);
if (lastModifiedDate != null && !lastModifiedDate.equals(formattedPicDate)) {
lastModifiedDate = formattedPicDate;
galleryItems.add(new Header(lastModifiedDate));
countgridsize++;
}
galleryItems.add(new Picture(file.getPath(), file.getName()));
}
}
}
this.adapter.setGalleryList(galleryItems);
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
final List<String> list = GalleryAdapter.list;
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Toast.makeText(GalleryBrowserActivity.this, "Delete Successfully..", Toast.LENGTH_SHORT).show();
for (String fileNameStr : list) {
String[] parts = fileNameStr.split("/");
String part1 = parts[5]; // 004
String part2 = parts[6]; // 034556
storage.deleteFile(".AliRehman/" + part1, part2);
}
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(GalleryBrowserActivity.this);
builder.setMessage("Are you sure?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
return true;
My adapter Class
public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context;
private final LayoutInflater layoutInflater;
private List<GalleryItem> galleryList = new ArrayList<>();
private OnItemClickListener mItemClickListener;
public static List<String> list;
public GalleryAdapter(Context context, LayoutInflater layoutInflater) {
this.context = context;
this.layoutInflater = layoutInflater;
}
public void setItemClickListener(OnItemClickListener listener) {
mItemClickListener = listener;
}
public void setGalleryList(List<GalleryItem> galleryList) {
this.galleryList = galleryList;
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return this.galleryList.get(position).getItemType();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == GalleryItem.HEADER_TYPE) {
return new HeaderHolder(layoutInflater.inflate(R.layout.item_header, parent, false));
} else {
return new PictureHolder(layoutInflater.inflate(R.layout.item_picture, parent, false));
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
GalleryItem item = galleryList.get(position);
if(getItemViewType(position) == GalleryItem.HEADER_TYPE) {
bindHeaderHolder((HeaderHolder) holder, (Header) item);
}
else {
bindPictureHolder((PictureHolder) holder, (Picture) item);
}
}
private void bindPictureHolder(final PictureHolder holder, Picture picture) {
Glide.with(context).load(Uri.fromFile(new File(picture.getPath()))).into(holder.pictureThumbnail);
boolean itemselected=picture.getSelected();
if(itemselected)
{
Log.d("ViewVisiblePicture", String.valueOf(picture.getPath()));
holder.overlayView.setVisibility(View.VISIBLE);
}
else
holder.overlayView.setVisibility(View.GONE);
}
private void bindHeaderHolder(HeaderHolder holder, Header header) {
holder.headerTxt.setText(header.getName());
}
#Override
public int getItemCount() {
return this.galleryList.size();
}
public void clearGallery() {
this.galleryList.clear();
notifyDataSetChanged();
}
public class HeaderHolder extends RecyclerView.ViewHolder {
private TextView headerTxt;
public HeaderHolder(View itemView) {
super(itemView);
this.headerTxt = (TextView) itemView.findViewById(R.id.headerTxt);
}
}
public class PictureHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
public ImageView pictureThumbnail;
public FrameLayout overlayView;
public PictureHolder pictureHolder;
private boolean[] thumbnailsselection;
public PictureHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
this.pictureThumbnail = (ImageView) itemView.findViewById(R.id.pictureThumbnail);
this.overlayView = (FrameLayout) itemView.findViewById(R.id.overlayView);
}
#Override
public boolean onLongClick(View view) {
list=new ArrayList<>();
if (mItemClickListener != null) {
mItemClickListener.onItemLongClick(getAdapterPosition());
this.overlayView.setVisibility(View.VISIBLE);
Picture model=(Picture) galleryList.get(getAdapterPosition());
//galleryList.get(getAdapterPosition());
model.setSelected(true);
list.add(model.getPath());
Log.d("Path1", model.getPath());
final int len = GalleryBrowserActivity.countgridsize;
int count = 0;
/* String selectImages = "";
for (int i = 0; i < len; i++) {
*//*if (pictureHolder..get(i).selection) {
count++;
selectImages = selectImages
+ pictureHolder.images.get(i).id + ",";
}*//*
this.overlayView.setVisibility(View.VISIBLE);
}
Log.d("Length", len+"");
if (count == 0) {
Toast.makeText(context,
"Please select at least one image",
Toast.LENGTH_LONG).show();
}*/
return true;
}
Log.d("hi","hello Image");
notifyDataSetChanged();
return false;
}
#Override
public void onClick(View v)
{
int position = getAdapterPosition();
Picture picture = (Picture) galleryList.get(position);
if(GalleryBrowserActivity.mActionMode!=null)
{
Log.d("Visiblilty","visible");
Picture model=(Picture) galleryList.get(getAdapterPosition());
if(model.getSelected()){
this.overlayView.setVisibility(View.GONE);
model.setSelected(false);
list.remove(model.getPath());
}else {
mItemClickListener.onItemClick(position, v, picture.getPath());
Toast.makeText(context, "visible" + picture.getPath(), Toast.LENGTH_LONG).show();
this.overlayView.setVisibility(View.VISIBLE);
model.setSelected(true);
list.add(model.getPath());
Log.d("Path2", model.getPath());
}
notifyDataSetChanged();
}
if (GalleryBrowserActivity.mActionMode==null) {
Log.d("Visible","invisible");
Toast.makeText(context,"invisible",Toast.LENGTH_LONG).show();
mItemClickListener.onItemClick(position, v, picture.getPath());
}
}
}
public interface OnItemClickListener
{
void onItemClick(int position, View v, String picturePath);
void onItemLongClick(int position);
}
}
I would suggest you to make below changes:
In GalleryAdapter :
From:
public static List<String> list;
To:
public static List< GalleryItem > list;
And add a function in your GalleryAdapter to remove items from your galleryList:
public void removeItem(GalleryItem item){
this.galleryList.remove(item);
notifyDataSetChanged();
}
And In PictureHolder:
#Override
public boolean onLongClick(View view) {
list=new ArrayList<>();
if (mItemClickListener != null) {
mItemClickListener.onItemLongClick(getAdapterPosition());
this.overlayView.setVisibility(View.VISIBLE);
GalleryItem model=(GalleryItem) galleryList.get(getAdapterPosition());
//galleryList.get(getAdapterPosition());
((Picture)model).setSelected(true);
list.add(model);
Log.d("Path1", ((Picture)model).getPath());
final int len = GalleryBrowserActivity.countgridsize;
int count = 0;
return true;
}
Log.d("hi","hello Image");
notifyDataSetChanged();
return false;
}
#Override
public void onClick(View v)
{
int position = getAdapterPosition();
GalleryItem picture = (GalleryItem) galleryList.get(position);
if(GalleryBrowserActivity.mActionMode!=null)
{
Log.d("Visiblilty","visible");
GalleryItem model=(GalleryItem) galleryList.get(getAdapterPosition());
if(model.getSelected()){
this.overlayView.setVisibility(View.GONE);
((Picture)model).setSelected(false);
list.remove(model);
}else {
mItemClickListener.onItemClick(position, v, picture.getPath());
Toast.makeText(context, "visible" + picture.getPath(), Toast.LENGTH_LONG).show();
this.overlayView.setVisibility(View.VISIBLE);
((Picture)model).setSelected(true);
list.add(model);
Log.d("Path2", model.getPath());
}
notifyDataSetChanged();
}
if (GalleryBrowserActivity.mActionMode==null) {
Log.d("Visible","invisible");
Toast.makeText(context,"invisible",Toast.LENGTH_LONG).show();
mItemClickListener.onItemClick(position, v, picture.getPath());
}
}
In the above code I am trying to update the list with selected GallryItem objects.
And While deleting item after the DialogInterface.BUTTON_POSITIVE is clicked, update the code like below:
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Toast.makeText(GalleryBrowserActivity.this, "Delete Successfully..", Toast.LENGTH_SHORT).show();
for (GalleryItem item : list) {
this.adapter.removeItem(item);
String fileNameStr = ((Picture)item).getPath();
String[] parts = fileNameStr.split("/");
String part1 = parts[5]; // 004
String part2 = parts[6]; // 034556
storage.deleteFile(".AliRehman/" + part1, part2);
}
break;
The above code will also update the galleryList inside adapter and notify the dataset change. Please let me know if you face any issue while implementing it.
you have to notify your adapter after you delete your image. like below.
arrayAdapter.notifyDataSetChanged();
in your example you have to write above line after you click Yes in your AlertDialog.
All you need to do is call notifyDataSetChanged() which will notify the RecyclerView to re-bin the views again, thereby deleting any item as necessary.
Just add a method in your adapter class,
mAdapter.notifyDataSetChanged();
If you know the position of the particular item which is getting deleted, then it is RECOMMENDED to use,
mAdapter.notifyItemChanged(position);
This will give you a nice animation effect while deleting the item.

ExpandableRecyclerAdapter How to force item to move up while expanding an item

This is my ExpandableRecyclerAdapter adapter
public class MyAdapter extends ExpandableRecyclerAdapter<MyAdapter.ProductParentViewHolder, MyAdapter.ProductChildViewHolder> {
private LayoutInflater mInflater;
private Context context;
private List<? extends ParentListItem> mParentItemList;
public MyAdapter(Context context, List<ParentListItem> itemList) {
super(itemList);
mInflater = LayoutInflater.from(context);
this.context = context;
this.mParentItemList = itemList;
}
#Override
public ProductParentViewHolder onCreateParentViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_parent, viewGroup, false);
return new ProductParentViewHolder(view);
}
#Override
public ProductChildViewHolder onCreateChildViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_child, viewGroup, false);
return new ProductChildViewHolder(view);
}
#Override
public void onBindParentViewHolder(ProductParentViewHolder crimeParentViewHolder, int i, ParentListItem parentListItem) {
Product product = (Product) parentListItem;
crimeParentViewHolder.productName.setText(product.getBrandName() + " " + product.getProductName());
Glide.with(context)
.load(product.getProductImagePath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(crimeParentViewHolder.thumbnail);
}
#Override
public void onBindChildViewHolder(ProductChildViewHolder productChildViewHolder, int i, Object childListItem) {
final ProductVariant productVariant = (ProductVariant) childListItem;
productChildViewHolder.mCrimeDateText.setText(productVariant.getVariantName());
productChildViewHolder.variantMrp.setText(context.getString(R.string.positive_amount, productVariant.getMRP()));
productChildViewHolder.variantMrp.setPaintFlags(productChildViewHolder.variantMrp.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
productChildViewHolder.variantSellPrice.setText(context.getString(R.string.positive_amount, productVariant.getSellPrice()));
//productChildViewHolder.variantMrp.setText(productVariant.getMRP().toString());
//productChildViewHolder.variantSellPrice.setText(productVariant.getSellPrice().toString());
if (productVariant.getInCart() == 0) {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.GONE);
} else {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.VISIBLE);
}
int quantity = productVariant.getInCart();
productChildViewHolder.btnProductDetailQty.setText(Integer.toString(quantity));
productChildViewHolder.btnProductDetailAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1);
//Utility.loadShoppingCartItems();
notifyDataSetChanged();
invalidateOptionsMenu();
//holder.db.addItem(new CartItem(1, productVariant.getProductID(), productVariant.getVariantID(), 1));
}
});
productChildViewHolder.btnProductDetailPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1 + productVariant.getInCart());
notifyDataSetChanged();
invalidateOptionsMenu();
//if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
//}
}
});
productChildViewHolder.btnProductDetailMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(productVariant.getInCart() - 1);
notifyDataSetChanged();
invalidateOptionsMenu();
if (productVariant.getInCart() == 0) {
//int count = holder.db.deleteSingleRow(productVariant.getProductID(), productVariant.getVariantID());
} else if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
}
//Utility.displayToast(holder.db.getItemsCount() + "");
}
});
//crimeChildViewHolder.mCrimeSolvedCheckBox.setChecked(productVariant.isSolved());
}
public class ProductParentViewHolder extends ParentViewHolder {
private static final float INITIAL_POSITION = 0.0f;
private static final float ROTATED_POSITION = 180f;
private final boolean HONEYCOMB_AND_ABOVE = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
public TextView productName;
public ImageView thumbnail;
public ImageButton mParentDropDownArrow;
public ProductParentViewHolder(View itemView) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.productName);
thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
// mParentDropDownArrow = (ImageButton) itemView.findViewById(R.id.parent_list_item_expand_arrow);
}
#SuppressLint("NewApi")
#Override
public void setExpanded(boolean expanded) {
super.setExpanded(expanded);
if (!HONEYCOMB_AND_ABOVE) {
return;
}
if (expanded) {
// mParentDropDownArrow.setRotation(ROTATED_POSITION);
} else {
// mParentDropDownArrow.setRotation(INITIAL_POSITION);
}
}
}
public class ProductChildViewHolder extends ChildViewHolder {
public TextView mCrimeDateText;
public TextView variantMrp;
public TextView variantSellPrice;
public Button btnProductDetailAddToCart, btnProductDetailPlus, btnProductDetailMinus;
public TextView btnProductDetailQty;
public ProductChildViewHolder(View itemView) {
super(itemView);
mCrimeDateText = (TextView) itemView.findViewById(R.id.variantName);
variantMrp = (TextView) itemView.findViewById(R.id.productVariantMrp);
variantSellPrice = (TextView) itemView.findViewById(R.id.productVariantSellPrice);
btnProductDetailAddToCart = (Button) itemView.findViewById(R.id.btnProductDetailAddToCart);
btnProductDetailPlus = (Button) itemView.findViewById(R.id.btnProductDetailPlus);
btnProductDetailMinus = (Button) itemView.findViewById(R.id.btnProductDetailMinus);
btnProductDetailQty = (TextView) itemView.findViewById(R.id.btnProductDetailQty);
}
}
}
When i am bottom of the page and click on item it expands, but exapnded child item doesn't shows to user because it is bottom in the screen.
I want to move that item up in the screen and show expanded items to user.
How can i do that?
You can simply use the method setSelectedGroup()
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
expandableListView.setSelectedGroup(groupPosition);
return true;
}
});
This will move the selected group to the top
EDIT
Finally I came out with a solution for your ExpandableRecyclerAdapter also. Simply put this method inside your adapter implementation. Also you will require the reference of the recyclerView inside the adapter which you can pass to the adapter at the time of initialization.
int lastPos = -1;
#Override
public void onParentListItemExpanded(int position) {
List<? extends ParentListItem> parentItemList = this.getParentItemList();
collapseAllParents();
int finalPos = position;
if (lastPos != -1 && lastPos < position) {
finalPos = position - parentItemList.get(lastPos).getChildItemList().size();
}
expandParent(finalPos);
mRecyclerView.smoothScrollToPosition(finalPos);
lastPos = position;
}
I found this issue at https://github.com/bignerdranch/expandable-recycler-view/issues/156 . Although the solution given there didn't work. Slight tweaking to that make it work.
Use this following code in your expandable listview click listener. Do something liket his
yourExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean onGroupClick(final ExpandableListView parent, View v, final int groupPosition, long id) {
....
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
parent.smoothScrollToPositionFromTop(groupPosition + 1, 0);
}
},100);
....
return true;
}
});
Use AnimatedExpandableListView

How to get context of an activity extending ListFragment from its adapter class?

This is my adapter class where I want to call startActionMode. I call it inside setActionMode method but got these errors:
Cannot cast from Context to ActivityFragment.
The method startActionMode(ActivityFragment.ActionModeCallback) is undefined for the type
ActivityFragment.
public class ListAdapter extends ArrayAdapter<ListGettersSetters>
{
ArrayList<ListGettersSetters> arrayListGettersSetters;
LayoutInflater layoutInflater;
Context context;
int Resource, i = 0, j = 0, checkedItemsCount = 0;
Animation animation1;
Animation animation2;
CheckBox flipCheckBox;
viewHolder holder;
ActionMode actionMode;
boolean isActionModeShowing;
static class viewHolder
{
public CheckBox imageView;
public TextView textViewName;
public TextView textViewData;
public TextView textViewDetails;
}
public ListAdapter(Context context, int resource, ArrayList<ListGettersSetters> arrayListGettersSetters)
{
super(context, resource, arrayListGettersSetters);
this.arrayListGettersSetters = arrayListGettersSetters;
Resource = resource;
this.context = context;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
animation1 = AnimationUtils.loadAnimation(context, R.anim.to_middle);
animation2 = AnimationUtils.loadAnimation(context, R.anim.from_middle);
isActionModeShowing = false;
}
#Override
public int getCount()
{
return arrayListGettersSetters.size();
}
#Override
public ListGettersSettersgetItem(int position)
{
return arrayListGettersSetters.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
holder = new viewHolder();
if(convertView == null)
{
convertView = layoutInflater.inflate(Resource, null);
holder.imageView = (CheckBox) convertView.findViewById(R.id.id_for_checkBox);
holder.textViewName = (TextView) convertView.findViewById(R.id.id_for_name_textView);
holder.textViewData = (TextView) convertView.findViewById(R.id.id_for_data_textView);
holder.textViewDetails = (TextView) convertView.findViewById(R.id.id_for_details_textView);
convertView.setTag(holder);
}
else
{
holder = (viewHolder) convertView.getTag();
}
holder.textViewName.setText(getItem(position).getName());
holder.textViewData.setText(getItem(position).getData());
holder.textViewDetails.setText(getItem(position).getDetails());
holder.imageView.setTag(position);
holder.imageView.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
flipCheckBox = (CheckBox) view;
flipCheckBox.clearAnimation();
flipCheckBox.setAnimation(animation1);
flipCheckBox.startAnimation(animation1);
setAnimListners(arrayListGettersSetters.get(Integer.parseInt(view.getTag().toString())));
}
});
return convertView;
}
private void setAnimListners(final ListGettersSetters listGettersSetters)
{
AnimationListener animationListener = new AnimationListener()
{
#Override
public void onAnimationStart(Animation animation)
{
if (animation == animation1)
{
flipCheckBox.clearAnimation();
flipCheckBox.setAnimation(animation2);
flipCheckBox.startAnimation(animation2);
}
else
{
listGettersSetters.setIsChecked(!listGettersSetters.isChecked());
setCount();
setActionMode();
}
}
public void setCount()
{
if (listGettersSetters.isChecked())
{
checkedItemsCount++;
}
else
{
if (checkedItemsCount != 0)
{
checkedItemsCount--;
}
}
Log.v("Checked items count", checkedItemsCount + "");
}
private void setActionMode()
{
if (checkedItemsCount > 0)
{
if (!isActionModeShowing)
{
actionMode = ((ActivityFragment) context).startActionMode(new ActivityFragment.ActionModeCallback(context));
isActionModeShowing = true;
}
}
else if (actionMode != null)
{
actionMode.finish();
isActionModeShowing = false;
}
if (actionMode != null)
{
actionMode.setTitle(String.valueOf(checkedItemsCount));
}
notifyDataSetChanged();
}
#Override
public void onAnimationRepeat(Animation animation)
{
}
#Override
public void onAnimationEnd(Animation animation)
{
}
};
animation1.setAnimationListener(animationListener);
animation2.setAnimationListener(animationListener);
}
This is my ActivityFragment class also in which i have implemented a class named ActionModeCallback which is called in my adapter class. Also when i take context of ActivityFragment in this inner class then also get the same errors.
public class ActivityFragment extends ListFragment
{
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState)
{
View view = layoutInflater.inflate(R.layout.folders_fragment_listview, null, false);
return view;
}
public static final class ActionModeCallback implements ActionMode.Callback
{
Context context;
public ActionModeCallback(Context context)
{
this.context = context;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem)
{
Toast toast = null;
ArrayList<FoldersFragmentGettersSetters> selectedListItems = new ArrayList<FoldersFragmentGettersSetters>();
StringBuilder selectedItems = new StringBuilder();
for (FoldersFragmentGettersSetters foldersFragmentGettersSetters : ((ActivityFragment ) context).listAdapter.arrayListGettersSetters)
{
if (foldersFragmentGettersSetters.isChecked())
{
selectedListItems.add(foldersFragmentGettersSetters);
}
}
if (menuItem.getTitle().equals("Delete"))
{
toast = Toast.makeText(context, "Delete: " + selectedItems.toString(), Toast.LENGTH_SHORT);
}
else if (menuItem.getTitle().equals("Archive"))
{
toast = Toast.makeText(context, "Archive: " + selectedItems.toString(), Toast.LENGTH_SHORT);
}
else if (menuItem.getTitle().equals("Mark unread"))
{
toast = Toast.makeText(context, "Mark unread: " + selectedItems.toString(), Toast.LENGTH_SHORT);
}
else if (menuItem.getTitle().equals("Move"))
{
toast = Toast.makeText(context, "Move: " + selectedItems.toString(), Toast.LENGTH_SHORT);
}
else if (menuItem.getTitle().equals("Remove star"))
{
toast = Toast.makeText(context, "Remove star: " + selectedItems.toString(), Toast.LENGTH_SHORT);
}
if (toast != null)
{
toast.show();
}
actionMode.finish();
return true;
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu)
{
menu.add("Delete").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Archive").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Mark unread").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Move").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Remove star").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
#Override
public void onDestroyActionMode(ActionMode actionMode)
{
((ActivityFragment ) context).inboxAdapter.checkedItemsCount = 0;
((ActivityFragment ) context).inboxAdapter.isActionModeShowing = false;
for (FoldersFragmentGettersSetters foldersFragmentGettersSettersItem : ((InboxFragment) context).inboxList)
{
foldersFragmentGettersSettersItem.setIsChecked(false);
}
((ActivityFragment ) context).listAdapter.notifyDataSetChanged();
Toast.makeText(context, "Action mode closed", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu)
{
return false;
}
}
}
Modify the constructor of your ListAdapter from
public ListAdapter(Context context, int resource, ArrayList<ListGettersSetters> arrayListGettersSetters)
to
public ListAdapter(ActivityFragment context, int resource, ArrayList<ListGettersSetters> arrayListGettersSetters)
One good approach would be to use callback.
Create callback interface (a listener) inside your adapter class.
Declare instance variable for interface, e.g. startActionModeCallback.
In adapter constructor, pass listener object and assign it to startActionModeCallback.
When you will create adapter's instance in ActivityFragment, pass it as listener and implement its callback method in fragment.
Call callback method anywhere in your adapter, and it will be listened by fragment.
Hope it makes sense to you. You can ask me for clarification. Good luck!
EXAMPLE
Adapter Class
public class ListAdapter extends ArrayAdapter<ListGettersSetters>
{
Interface StartActionInterface
{
public void startActionMode();
}
//declare other instance variables and add following
StartActionInterface startActionModeListener;
//change your constructor as:
public ListAdapter(Context context, int resource, ArrayList<ListGettersSetters> arrayListGettersSetters, StartActionInterface listener)
{
//normal code
startActionModeListener = listener;
}
}
ActivityFragment
public class ActivityFragment extends ListFragment implements StartActionInterface
{
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState)
{
View view = layoutInflater.inflate(R.layout.folders_fragment_listview, null, false);
////////initialize adapter and pass `this` in last argument
return view;
}
//Implement callback method. Also implement `setActionMode()` method here in fragment.
void startActionMode()
{
setActionMode();
}
}
Here in function setActionMode(), replace following line:
if (!isActionModeShowing)
{
actionMode = ((ActivityFragment) context).startActionMode(new ActivityFragment.ActionModeCallback(context));
isActionModeShowing = true;
}
with:
if (!isActionModeShowing)
{
actionMode = getActivity().startActionMode(new ActionModeCallback(getActivity()));
isActionModeShowing = true;
}

Categories

Resources