progress bar only on current item, not on others.
when i long clicking on item the progress bar shown on to or more items and changing position.
i want show progressbar only on clicked item not other items
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
String getidtoextra = ((TextView) v.findViewById(R.id.wallid)).getText().toString();
final ProgressBar itemprogress = (ProgressBar) v.findViewById(R.id.itemprogress);
itemprogress.setVisibility(View.VISIBLE);
DownloadManager manager = new DownloadManager();
String destPath = Environment.getExternalStorageDirectory() + File.separator + "Kaghaz Divari/" + getidtoextra + "_KD.jpg";
DownloadRequest request = new DownloadRequest()
.setDownloadId(pos)
.setUrl("http://www.wenenus.com/www.samankd.com/android/wallpaper/download.php?id=" + getidtoextra)
.setDestFilePath(destPath)
.setDownloadListener(new DownloadListener() {
#Override
public void onStart(int downloadId, long totalBytes) {
}
#Override
public void onRetry(int downloadId) {
itemprogress.setProgress(0);
}
#Override
public void onProgress(int downloadId, long bytesWritten, long totalBytes) {
itemprogress.setProgress((int) ((bytesWritten * 100) / totalBytes));
}
#Override
public void onSuccess(int downloadId, String filePath) {
itemprogress.setVisibility(View.GONE);
}
#Override
public void onFailure(int downloadId, int statusCode, String errMsg) {
itemprogress.setVisibility(View.GONE);
}
});
manager.add(request);
return onLongListItemClick(v,pos,id);
}
});
My custom adapter
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) convertView = inflater.inflate(R.layout.list_row, null);
ImageView thumbNail = (ImageView) convertView.findViewById(R.id.thumbnail);
ImageView isdownloaded = (ImageView) convertView.findViewById(R.id.isdownloaded);
LinearLayout newwallpaperarea = (LinearLayout) convertView.findViewById(R.id.newwallpaperarea);
TextView downloads = (TextView)convertView.findViewById(R.id.dlstxt);
TextView rating = (TextView)convertView.findViewById(R.id.ratingtxt);
TextView wallid = (TextView)convertView.findViewById(R.id.wallid);
// getting movie data for the row
Movie m = movieItems.get(position);
File is_wall_dl = new File(Environment.getExternalStorageDirectory()+ "/Kaghaz Divari/"+m.getThumbnailUrl());
File is_wall_dl_id = new File(Environment.getExternalStorageDirectory()+ "/Kaghaz Divari/"+m.getId()+"_KD.jpg");
if(is_wall_dl.exists() || is_wall_dl_id.exists()){
isdownloaded.setVisibility(View.VISIBLE);
}
else{
isdownloaded.setVisibility(View.GONE);
}
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
String tsnew = ts+"000";
long realtime = Long.parseLong(tsnew);
String walldate = m.getDate();
long walldateall = Long.parseLong(walldate);
long walldatefinal = walldateall+86400000;
if (realtime > walldatefinal) {
newwallpaperarea.setVisibility(View.GONE);
} else {
newwallpaperarea.setVisibility(View.VISIBLE);
}
// thumbnail image
Ion.with(thumbNail)
.placeholder(R.drawable.skd_small_bg_200x200)
.error(R.drawable.skd_small_bg_200x200_error)
.load("http://www.wenenus.com/www.samankd.com/android/wallpaper/wallpaper/200/200/80/1/" + m.getThumbnailUrl());
downloads.setText(m.getDownloads());
rating.setText(m.getRating());
wallid.setText(m.getId());
return convertView;
}
}
Related
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
Currently I am using a CursorAdapter for a chat app's chat listview. I populated the latest 20 chat record from SQLite for my list, and I want to load earlier chat records when I scroll to the top just like other chat app. How to achieve this? should I use CursorAdapter? Or doing another query then merge another cursor when scroll to the top of the listview?
Here is my code of CursorAdapter, please help and give suggestions.
public class ChatViewAdapter extends CursorAdapter{
private static final int MSG_TIME_SHOW_DELAY = 300000;
private String mUser;
private Context mContext;
private XmppBinder mXmppBinder;
private boolean mIsMultChat;
private LayoutInflater mInflater;
private Map<String, SoftReference<XmppVcard>> mVcards;
private Map<String, SoftReference<Bitmap>> mCache;
private View.OnClickListener mResendClickListener;
private View.OnClickListener mOnImageClickListener;
private View.OnClickListener mOnAudioClickListener;
private Handler mHandler;
public ChatViewAdapter(Context context,Cursor cursor,XmppBinder xmppBinder,String currentUser){
super(context,cursor,true);
mContext = context;
mInflater = LayoutInflater.from(context);
mUser = currentUser;
mXmppBinder = xmppBinder;
mCache = new HashMap<String, SoftReference<Bitmap>>();
mVcards = new HashMap<String, SoftReference<XmppVcard>>();
}
public void setOnImageClickListener(View.OnClickListener listener){
mOnImageClickListener = listener;
}
public void setOnAudioClickListener(View.OnClickListener listener){
mOnAudioClickListener = listener;
}
private int transfer(int position) {
return getCount() - position - 1;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return super.getDropDownView(transfer(position), convertView, parent);
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
position = transfer(position);
if (position < 0 || position > getCursor().getCount() - 1) {
return null;
}
return super.getItem(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return super.getItemId(transfer(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return super.getView(transfer(position), convertView, parent);
}
public void setResendClickListener(View.OnClickListener listener) {
mResendClickListener = listener;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View convertView = mInflater.inflate(R.layout.list_item_chat_msg,
null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.systemTip = (TextView) convertView
.findViewById(R.id.chat_item_system_msg);
viewHolder.leftView = convertView.findViewById(R.id.chat_item_left_view);
viewHolder.leftAvartar = (HexagonImageView)convertView.findViewById(R.id.chat_item_from_avatar);
viewHolder.leftMsgTxt = (TextView)convertView.findViewById(R.id.chat_msg_from_text);
viewHolder.leftMsgImg = (AspectRatioMaskImageView)convertView.findViewById(R.id.chat_msg_from_image);
viewHolder.rightView = convertView.findViewById(R.id.chat_item_right_view);
viewHolder.rightAvartar = (HexagonImageView)convertView.findViewById(R.id.chat_item_to_avatar);
viewHolder.rightMsgTxt = (TextView)convertView.findViewById(R.id.chat_msg_to_text);
viewHolder.rightMsgImg = (AspectRatioMaskImageView)convertView.findViewById(R.id.chat_msg_to_image);
convertView.setTag(viewHolder);
return convertView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewHolder = (ViewHolder)view.getTag();
if (viewHolder!=null){
final String messageOwner = cursor.getString(cursor.getColumnIndex(MsgManager.MsgColumns.SENDER));
boolean isComMsg = !messageOwner.startsWith(mUser);
long date = cursor.getLong(cursor.getColumnIndex(MsgManager.MsgColumns.CREATE_DATE));
viewHolder.systemTip.setText(DateFormat.format(
"yyyy-MM-dd hh:mm:ss", new Date(date)));
viewHolder.systemTip.setVisibility(View.GONE);
int position = cursor.getPosition();
Cursor nextCursor = (Cursor)getItem(cursor.getCount()-cursor.getPosition()-2);
if (nextCursor!=null){
long date2 = cursor.getLong(cursor
.getColumnIndex(MsgManager.MsgColumns.CREATE_DATE));
if (Math.abs(date2 - date) > MSG_TIME_SHOW_DELAY) {
viewHolder.systemTip.setVisibility(View.VISIBLE);
}
}
cursor.moveToPosition(position);
if (cursor.getPosition()==cursor.getPosition()-1){
viewHolder.systemTip.setVisibility(View.VISIBLE);
}
String content = cursor.getString(cursor.getColumnIndex(MsgManager.MsgColumns.CONTENT));
HushLog.getInstance().i("msg %s",content);
ChatMessage message= ChatMessage.fromString(content);
TextView userTextView =null;
HexagonImageView userImageView=null;
if (isComMsg){
viewHolder.rightView.setVisibility(View.GONE);
viewHolder.leftView.setVisibility(View.VISIBLE);
userImageView = viewHolder.leftAvartar;
dealMsg(cursor.getInt(0),
viewHolder.leftMsgTxt,
viewHolder.leftMsgImg,
message,
isComMsg);
} else {
viewHolder.rightView.setVisibility(View.VISIBLE);
viewHolder.leftView.setVisibility(View.GONE);
userImageView = viewHolder.rightAvartar;
dealMsg(cursor.getInt(0),
viewHolder.rightMsgTxt,
viewHolder.rightMsgImg,
message,
isComMsg);
}
final HexagonImageView imgView = userImageView;
SoftReference<XmppVcard> softReference = mVcards.get(messageOwner);
if (softReference!=null && softReference.get()!=null){
XmppVcard vcard = softReference.get();
if (vcard.getGender().equals("M")){
userImageView.setBorderColor(Color.BLUE);
}
} else {
mXmppBinder.execute(new Runnable() {
#Override
public void run() {
final XmppVcard vcard = new XmppVcard(mXmppBinder.getServiceContext());
vcard.load(mXmppBinder.getXmppConnection(),messageOwner);
mVcards.put(messageOwner, new SoftReference<XmppVcard>(vcard));
if (vcard.getGender().equals("M") && imgView!=null){
imgView.setBorderColor(Color.BLUE);
}
}
});
}
userImageView.setImageResource(R.drawable.default_avatar);
AsyncImageLoader.loadBitmapFromStore(messageOwner,new ImageLoaderListener() {
#Override
public void onImageLoaded(String url, Bitmap bitmap) {
imgView.setImageBitmap(bitmap);
}
});
}
}
private void dealMsg(int id,
TextView bodyTextView,
AspectRatioMaskImageView bodyImageView,
ChatMessage message,
boolean isComMsg){
String content = message.getBody();
ChatMessage.MsgType msgType = message.getType();
bodyTextView.setOnClickListener(null);
bodyTextView.setVisibility(View.GONE);
bodyImageView.setVisibility(View.GONE);
if (ChatMessage.MsgType.TEXT.equals(msgType)){
bodyTextView.setVisibility(View.VISIBLE);
bodyImageView.setVisibility(View.GONE);
bodyTextView.setText(content);
} else if (ChatMessage.MsgType.IMAGE.equals(msgType)){
bodyTextView.setVisibility(View.GONE);
bodyImageView.setVisibility(View.VISIBLE);
String filePath = message.getBody();
} else if (ChatMessage.MsgType.AUDIO.equals(msgType)){
bodyTextView.setVisibility(View.VISIBLE);
bodyImageView.setVisibility(View.GONE);
try {
String audioPath = message.getAudioPath();
String duration = message.getAudioDuration();
bodyTextView.setText(duration+"\"");
} catch (Exception e){
}
}
}
private class ViewHolder {
TextView systemTip;
View leftView;
HexagonImageView leftAvartar;
TextView leftMsgTxt;
AspectRatioMaskImageView leftMsgImg;
View rightView;
HexagonImageView rightAvartar;
TextView rightMsgTxt;
AspectRatioMaskImageView rightMsgImg;
}
}
I want to populate a ListView with different layouts for odd and even rows. It should look like this:
I use two objects "OddListItem" and "EvenListItem" to store/access the data. I do not know how to pass both objects to my custom listview adapter and get the correct view.
My object classes:
public class OddListItem {
private String time_start;
private String time_end;
private String location;
public OddListItem(String time_start, String time_end, String location) {
super();
this.time_start = time_start;
this.time_end = time_end;
this.location = location;
}
// getters and setters
void setTimeStart(String time_start) {
this.time_start = time_start;
}
void setTimeEnd(String time_end) {
this.time_end = time_end;
}
void setLocation(String location) {
this.location = location;
}
public String getTimeStart() {
return time_start;
}
public String getTimeEnd() {
return time_end;
}
public String getLocation() {
return location;
}
}
public class EvenListItem {
private String image;
private String location;
public EvenListItem (String image, String location) {
super();
this.image = image;
this.location = location;
}
// getters and setters
void setImage(String image) {
this.image = image;
}
void setLocation(String location) {
this.location = location;
}
public String getImage() {
return image;
}
public String getLocation() {
return location;
}
}
MyCustomAdapter:
public class MyCustomAdapter extends BaseAdapter {
// Tag for Logging
private static final String TAG = "MyCustomAdapter";
int type;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<OddListItem> mData = new ArrayList<OddListItem>();
private LayoutInflater mInflater;
//private TreeSet mSeparatorsSet = new TreeSet();
private Context context;
public MyCustomAdapter(Context context) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
}
public void addItem(final OddListItem item) {
mData.add(item);
//The notification is not necessary since the items are not added dynamically
//notifyDataSetChanged();
}
public void addSeparatorItem(final OddListItem item) {
mData.add(item);
//The notification is not necessary since the items are not added dynamically
//notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
/*if ((position%2) == 0){
type = TYPE_ITEM;
} else {
type = TYPE_SEPARATOR;
}
return type;*/
return position%2;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public OddListItem getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
Log.d(TAG, "getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
//inflate the new layout
convertView = mInflater.inflate(R.layout.detail_list_row_odd, parent, false);
holder.tv_time_from = (TextView) convertView.findViewById(R.id.tv_time_from);
holder.tv_time_to = (TextView) convertView.findViewById(R.id.tv_time_to);
holder.tv_current_location_odd = (TextView) convertView.findViewById(R.id.tv_current_location_odd);
//fill the layout with values
/*holder.tv_time_from.setText("12:34");
holder.tv_time_to.setText("12:37");
holder.tv_current_location_odd.setText("Aktueller Standort");*/
holder.tv_time_from.setText(mData.get(position).getTimeStart());
holder.tv_time_to.setText(mData.get(position).getTimeEnd());
holder.tv_current_location_odd.setText(mData.get(position).getLocation());
break;
case TYPE_SEPARATOR:
//inflate the new layout
convertView = mInflater.inflate(R.layout.detail_list_row_even, parent, false);
holder.tv_current_location_even = (TextView) convertView.findViewById(R.id.tv_current_location_even);
holder.img_transport = (ImageView) convertView.findViewById(R.id.img_transport);
//fill the layout with values
holder.tv_current_location_even.setText("Hauptbahnhof");
holder.img_transport.setImageDrawable(context.getResources().getDrawable(R.drawable.rollator));
break;
default:
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
private static class ViewHolder {
public TextView tv_time_from;
public TextView tv_time_to;
public TextView tv_current_location_odd;
public TextView tv_current_location_even;
public ImageView img_transport;
}
}
Here I generate the data and call the adapter:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_connection);
generateData();
//fill ListView with custom content from MyCustomAdapter class
mAdapter = new MyCustomAdapter(getApplicationContext());
for (int i = 1; i < odd_items.size(); i++) {
mAdapter.addItem(odd_items.get(i));
if (i % 1 == 0) {
mAdapter.addSeparatorItem(odd_items.get(i));
}
}
setListAdapter(mAdapter);
//set duration text
tv_duration = (TextView)findViewById(R.id.tv_duration);
tv_duration.setText("Dauer: 22 Minuten");
}
private void generateData() {
odd_items = new ArrayList<OddListItem>();
odd_items.add(new OddListItem("12:34", "", "Aktueller Standort"));
odd_items.add(new OddListItem("12:37", "12:37", "TUM"));
odd_items.add(new OddListItem("12:42", "12:42", "Hauptbahnhof Nord"));
odd_items.add(new OddListItem("12:48", "12:48", "Hauptbahnhof"));
even_items = new ArrayList<EvenListItem>();
even_items.add(new EvenListItem("R.drawable.rollator", "3 Minuten Fußweg"));
even_items.add(new EvenListItem("R.drawable.bus", "Richtung Hauptbahnhof Nord"));
even_items.add(new EvenListItem("R.drawable.rollator", "6 Minuten Fußweg"));
mData = new Data(odd_items, even_items);
}
Any help would be great. Maybe there is also a better approach then please let me know.
I would create a Single list of Items
public class Items {
private String time_start;
private String time_end;
private String location;
private int image;
private String locationeven;
private int oddoreven;
public String getTime_start() {
return time_start;
}
public void setTime_start(String time_start) {
this.time_start = time_start;
}
public String getTime_end() {
return time_end;
}
public void setTime_end(String time_end) {
this.time_end = time_end;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getLocationeven() {
return locationeven;
}
public void setLocationeven(String locationeven) {
this.locationeven = locationeven;
}
public int getOddoreven() {
return oddoreven;
}
public void setOddoreven(int oddoreven) {
this.oddoreven = oddoreven;
}
}
In onCreate of Activity call
generateData() ;
Then
ArrayList<Items> oddorevenlist = new ArrayList<Items>();
private void generateData() {
Items item1 = new Items();
item1.setTime_start("12:34");
item1.setTime_end("");
item1.setLocation("Aktueller Standort");
item1.setOddoreven(0);
oddorevenlist.add(item1);
Items item2 = new Items();
item2.setImage(R.drawable.ic_launcher);
item2.setLocationeven("3 Minuten Fußweg");
item2.setOddoreven(1);
oddorevenlist.add(item2);
Items item3 = new Items();
item3.setTime_start("12:37");
item3.setTime_end("12:37");
item3.setLocation("Tum");
item3.setOddoreven(0);
oddorevenlist.add(item3);
Items item4 = new Items();
item4.setImage(R.drawable.ic_launcher);
item4.setLocationeven("Richtung Hauptbahnhof Nord");
item4.setOddoreven(1);
oddorevenlist.add(item4);
Items item5 = new Items();
item5.setTime_start("12:42");
item5.setTime_end("12:42");
item5.setLocation("Hauptbahnhof Nord");
item5.setOddoreven(0);
oddorevenlist.add(item5);
Items item6 = new Items();
item6.setImage(R.drawable.ic_launcher);
item6.setLocationeven("R6 Minuten Fußweg");
item6.setOddoreven(1);
oddorevenlist.add(item6);
Items item7 = new Items();
item7.setTime_start("12:48");
item7.setTime_end("12:48");
item7.setLocation("HHauptbahnhof");
item7.setOddoreven(0);
oddorevenlist.add(item7);
MyCustomAdapter mAdapter = new MyCustomAdapter(this,oddorevenlist);
setListAdapter(mAdapter);
}
Adapter code
public class MyCustomAdapter extends BaseAdapter {
// Tag for Logging
private static final String TAG = "MyCustomAdapter";
int type;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private ArrayList<Items> oddorevenlist ;
private LayoutInflater mInflater;
private Context context;
public MyCustomAdapter(Context context, ArrayList<Items> oddorevenlist) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.oddorevenlist = oddorevenlist;
}
#Override
public int getItemViewType(int position) {
if (oddorevenlist.get(position).getOddoreven()==0){
type = TYPE_ITEM;
} else if (oddorevenlist.get(position).getOddoreven()==1) {
type = TYPE_SEPARATOR;
}
return type;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return oddorevenlist.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
Log.d(TAG, "getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
//inflate the new layout
convertView = mInflater.inflate(R.layout.row_odd, parent, false);
holder.tv_time_from = (TextView) convertView.findViewById(R.id.tv_time_from);
holder.tv_time_to = (TextView) convertView.findViewById(R.id.tv_time_to);
holder.tv_current_location_odd = (TextView) convertView.findViewById(R.id.tv_current_location_odd);
holder.tv_time_from.setText(oddorevenlist.get(position).getTime_start());
holder.tv_time_to.setText(oddorevenlist.get(position).getTime_end());
holder.tv_current_location_odd.setText(oddorevenlist.get(position).getLocation());
break;
case TYPE_SEPARATOR:
//inflate the new layout
convertView = mInflater.inflate(R.layout.row_even, parent, false);
holder.tv_current_location_even = (TextView) convertView.findViewById(R.id.tv_current_location_even);
holder.img_transport = (ImageView) convertView.findViewById(R.id.img_transport);
//fill the layout with values
holder.tv_current_location_even.setText(oddorevenlist.get(position).getLocationeven());
holder.img_transport.setImageResource(R.drawable.ic_launcher);
break;
default:
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
private static class ViewHolder {
public TextView tv_time_from;
public TextView tv_time_to;
public TextView tv_current_location_odd;
public TextView tv_current_location_even;
public ImageView img_transport;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
}
Snap
This question already exists:
OnListItemClick event is not working
Closed 8 years ago.
I have been facing a problem...there is a five different Java classes MainActivity, Application, ApplicationAdapter, FetchData ,FetchDataListener.. I am binding mysql data from api in ListView... but I am trying to fire a click event on ListView but I am getting error....here is code...
MainActivity.java
#Override
public void onFetchComplete(List<Applicity> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
public void onListItemClick(ListView l, View v, int position, long id) {
Applicity app= new Applicity();
int p =app.getPosition(position);
Toast.makeText(this,p,Toast.LENGTH_LONG).show();
}
ApplicationAdapter.java
public class ApplicationAdapter extends ArrayAdapter<Applicity>{
private List<Applicity> items;
public ApplicationAdapter(Context context, List<Applicity> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
}
Applicity app = items.get(position);
if(app != null) {
ImageView icon = (ImageView)v.findViewById(R.id.appIcon);
TextView titleText = (TextView)v.findViewById(R.id.titleTxt);
LinearLayout ratingCntr = (LinearLayout)v.findViewById(R.id.ratingCntr);
TextView dlText = (TextView)v.findViewById(R.id.dlTxt);
if(icon != null) {
Resources res = getContext().getResources();
String sIcon = "com.sj.jsondemo:drawable/" + app.getIcon();
icon.setImageDrawable(res.getDrawable(res.getIdentifier(sIcon, null, null)));
}
if(titleText != null) titleText.setText(app.getTitle());
if(dlText != null) {
NumberFormat nf = NumberFormat.getNumberInstance();
dlText.setText(nf.format(app.getTotalDl())+" dl");
}
if(ratingCntr != null && ratingCntr.getChildCount() == 0) {
/*
* max rating: 5
*/
for(int i=1; i<=5; i++) {
ImageView iv = new ImageView(getContext());
if(i <= app.getRating()) {
iv.setImageDrawable(getContext().getResources().getDrawable(R.drawable.start_checked));
}
else {
iv.setImageDrawable(getContext().getResources().getDrawable(R.drawable.start_unchecked));
}
ratingCntr.addView(iv);
}
}
}
return v;
}
}
Applicity.java
public class Applicity {
private String title;
private long totalDl;
private int rating;
public int position;
private String icon;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getTotalDl() {
return totalDl;
}
public void setTotalDl(long totalDl) {
this.totalDl = totalDl;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public int getPosition(int arg){
return position;
}
}
Use OnItemClickListener. You're creating a new custom method instead of OnItemClickListener.
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do something here.
}
});
I have a GridView and adapter for GridView (BasketAdapter extends BaseAdapter).
I load data in GridView from sharedpref file.
After I change data, I resave sharedpref file with data and call notifyDataSetChanged().
But notifyDataSetChanged() doesn't work unfortunately.
If I create new adapter and set it to my GridView, it works.
Can anyone help me with this issue?
Here is my code:
public class FragmentBasket extends SherlockFragment {
// my gridview
GridView gvCatalogAllStoneBasket;
// list of data from shared pref
ArrayList<CatalogItem> catalogItemBasket = new ArrayList<CatalogItem>();
ActionMode mode;
public static CatalogItem catalogItem;
// id variables for actionmode's actions
static final int ID_DELETE = 1;
static final int ID_EDIT = 2;
// shared pref id string
static String SHARED_PREFS_FILE = "basket";
// my adapter
BasketAdapter adapter = null;
public FragmentBasket() {
}
#Override
public void onStart() {
super.onStart();
// loading saved data from file
new GetCatalogAllStoneBasket().execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Receiver receiver = new Receiver();
IntentFilter intentFilterAdd = new IntentFilter("com.example.myproject.ADD_ITEM_BASKET");
IntentFilter intentFilterEdit = new IntentFilter("com.example.myproject.EDIT_ITEM_BASKET");
IntentFilter intentFilterDelete = new IntentFilter("com.example.myproject.DELETE_ITEM_BASKET");
getActivity().registerReceiver(receiver, intentFilterAdd);
getActivity().registerReceiver(receiver, intentFilterEdit);
getActivity().registerReceiver(receiver, intentFilterDelete);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid, container, false);
gvCatalogAllStoneBasket = (GridView)view.findViewById(R.id.gvCatalogAllStoneBasket);
gvCatalogAllStoneBasket.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// start action mode and send id of clicked item
mode = getSherlockActivity().startActionMode(new ActionModeOfBasket(String.valueOf(view.getTag())));
return false;
}
});
return view;
}
private final class ActionModeOfBasket implements ActionMode.Callback
{
String itemId;
public ActionModeOfBasket(String itemId) {
// get id from clicked item
this.itemId = itemId;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.add(0, ID_EDIT, 0, "Edit")
.setIcon(android.R.drawable.ic_menu_edit)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
menu.add(0, ID_DELETE, 1, "Delete")
.setIcon(android.R.drawable.ic_menu_delete)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// get file
SharedPreferences sPref = getActivity().getSharedPreferences(SHARED_PREFS_FILE, getActivity().MODE_PRIVATE);
// open file for reading, writing
BasketHelper bHelper = new BasketHelper(sPref, getActivity());
switch (item.getItemId())
{
// if clicked del button
case ID_DELETE:
// delete item
bHelper.DelItem(itemId);
mode.finish();
catalogItemBasket = bHelper.GetAllItems();
break;
// if clicked edit button
case ID_EDIT:
// edit item
bHelper.EditItem(itemId, getFragmentManager());
mode.finish();
catalogItemBasket = bHelper.GetAllItems();
break;
}
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
}
class GetCatalogAllStoneBasket extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
SharedPreferences sPref = getActivity().getSharedPreferences(FragmentCatalogStonePosition.SHARED_PREFS_FILE, getActivity().MODE_PRIVATE);
try {
if(sPref.getString(FragmentCatalogStonePosition.TASK, null) != null)
{
BasketHelper bHelper = new BasketHelper(sPref, getActivity());
catalogItemBasket = bHelper.GetAllItems();
}
} catch (Exception e) {
Log.d(MainActivity.tag, e.getMessage() + " " + e.getCause());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
adapter = new BasketAdapter(getActivity(), catalogItemBasket);
gvCatalogAllStoneBasket.setAdapter(adapter);
}
}
class Receiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().toString() == "com.example.myproject.ADD_ITEM_BASKET")
{
}
else if(intent.getAction().toString() == "com.example.myproject.EDIT_ITEM_BASKET")
{
// this code doesn't work (((
adapter.notifyDataSetChanged();
// this one successfully works
BasketAdapter bAdapter = new BasketAdapter(getActivity(), catalogItemBasket);
gvCatalogAllStoneBasket.setAdapter(bAdapter);
}
else if(intent.getAction().toString() == "com.example.myproject.DELETE_ITEM_BASKET")
{
}
}
}
class BasketAdapter extends BaseAdapter
{
Context context = null;
ArrayList<CatalogItem> data = null;
public BasketAdapter(Context context, ArrayList<CatalogItem> data) {
this.context = context;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
public CatalogItem getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null)
{
LayoutInflater inflater = getLayoutInflater(null);
view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid_item, parent, false);
CatalogItem item = getItem(position);
((TextView)view.findViewById(R.id.tvCatalogItemBasketName)).setText(item.name + " / " + item.code);
Double gPrice = Double.valueOf(item.price) * Double.valueOf(item.count);
((TextView)view.findViewById(R.id.tvCatalogItemBasketCount)).setText(String.valueOf(item.count));
((TextView)view.findViewById(R.id.tvCatalogItemBasketGeneralPrice)).setText(String.valueOf(gPrice));
((TextView)view.findViewById(R.id.tvCatalogItemBasketDescription)).setText(item.description);
final ImageView imgView = (ImageView)view.findViewById(R.id.ivCatalogItemBasketImage);
String strURL = "http://myproject.ua/images/stock/" + item.folder + "/" + item.images + "_800x600.jpg";
ImageLoaderConfiguration config = ImageHelper.ImageConfig(getActivity().getApplicationContext());
DisplayImageOptions options = ImageHelper.ImageOptions();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
final ProgressBar pImgDialog = (ProgressBar)view.findViewById(R.id.pbImage);
imageLoader.displayImage(strURL, imgView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
pImgDialog.setVisibility(View.VISIBLE);
imgView.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
});
view.setTag(item.catalog_id);
}
return view;
}
}
}
Your convertView isn't null in case the View is recycled, so your getView() should be something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null)
{
LayoutInflater inflater = getLayoutInflater(null);
view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid_item, parent, false);
}
CatalogItem item = getItem(position);
((TextView)view.findViewById(R.id.tvCatalogItemBasketName)).setText(item.name + " / " + item.code);
Double gPrice = Double.valueOf(item.price) * Double.valueOf(item.count);
((TextView)view.findViewById(R.id.tvCatalogItemBasketCount)).setText(String.valueOf(item.count));
((TextView)view.findViewById(R.id.tvCatalogItemBasketGeneralPrice)).setText(String.valueOf(gPrice));
((TextView)view.findViewById(R.id.tvCatalogItemBasketDescription)).setText(item.description);
final ImageView imgView = (ImageView)view.findViewById(R.id.ivCatalogItemBasketImage);
String strURL = "http://myproject.ua/images/stock/" + item.folder + "/" + item.images + "_800x600.jpg";
ImageLoaderConfiguration config = ImageHelper.ImageConfig(getActivity().getApplicationContext());
DisplayImageOptions options = ImageHelper.ImageOptions();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
final ProgressBar pImgDialog = (ProgressBar)view.findViewById(R.id.pbImage);
imageLoader.displayImage(strURL, imgView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
pImgDialog.setVisibility(View.VISIBLE);
imgView.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
});
view.setTag(item.catalog_id);
return view;
}
and since you have your own ArrayList inside your adapter, you have to update this one as well. Just add this method to your BasketAdapter:
public void changeModelList(List<CatalogItem> models) {
this.data = models;
notifyDataSetChanged();
}
and use it instead of notifyDataSetChanged().
it's not tested, but i think this is your problem.