I have a custom ListView. This ListView contain of 1 Image and 3 TextView. How can I click on ImageView and get current position. (Do not click to other elements, only ImageView)
In your custom adapter class, you are havinggetView(.. .. ..) method :
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
// >>> >>> ^^^^^^ This is your posotion = index
View row = convertView;
Your_Holder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(resId, parent, false);
holder = new Your_Holder();
....
....
holder.yourImageView = (ImageView) row.findViewById(R.id.yourImageID);
....
....
row.setTag(holder);
}
else{
holder = (Your_Holder)row.getTag();
}
// Set here your images click event
holder.yourImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Position = " + position)
}
});
}
Related
I have a listview containing items name and price i made my code so when i click on one item it displays its price in a small dialog box at the bottom of the screen but now when i click another item i want to add that item's price to the first one and so on..
Here is my code for now:
#Override
public View getView(final int position, final View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontent, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = rowView.findViewById(R.id.name);
viewHolder.textData = rowView.findViewById(R.id.details);
viewHolder.textImage = rowView.findViewById(R.id.price);
viewHolder.producticon = rowView.findViewById(R.id.producticon);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getProname() + "");
viewHolder.textData.setText(parkingList.get(position).getData());
viewHolder.textImage.setText(parkingList.get(position).getImage());
Picasso.with(context).load(parkingList.get(position).getProducticon()).into(viewHolder.producticon);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
final int count = 0;
LayoutInflater inflater2 = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final Dialog mBottomSheetDialog = new Dialog(context, R.style.MaterialDialogSheet);
View content = inflater2.inflate(R.layout.activity_main2, null);
mBottomSheetDialog.setContentView(content);
TextView textView = (TextView) content.findViewById(R.id.mebuyss);
final TextView itemcount = (TextView) content.findViewById(R.id.itemcount);
Button plus = (Button) content.findViewById(R.id.plus);
Button minus = (Button) content.findViewById(R.id.minus);
Button finish = (Button) content.findViewById(R.id.finishgettingitem);
textView.setText(parkingList.get(position).getProname());
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
itemcount.setText(String.valueOf(counter));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter --;
if(counter<0){
counter=0;
}
itemcount.setText(String.valueOf(counter));
}
});
final Dialog mBottomSheetDialog2 = new Dialog(context, R.style.MaterialDialogSheet);
final View content2 = inflater2.inflate(R.layout.smalldialog, null);
final TextView total = (TextView) content2.findViewById(R.id.totalpriceofsmalldialog);
total.setText(null);
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String get = itemcount.getText().toString();
Float last = Float.parseFloat(get) * Float.parseFloat(parkingList.get(position).getImage());
mBottomSheetDialog.dismiss();
mBottomSheetDialog2.setContentView(content2);
mBottomSheetDialog2.setCancelable(false);
mBottomSheetDialog2.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog2.getWindow().setGravity(Gravity.BOTTOM);
total.setText(String.valueOf(last));
mBottomSheetDialog2.show();
mBottomSheetDialog2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mBottomSheetDialog2.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
doneonce = true;
}
});
// if (doneonce = true){
// Float priceofitem = parseFloat(parkingList.get(position).getImage());
// Float currentprice = parseFloat(total.getText().toString());
// Float finalfloat = priceofitem * currentprice;
// total.setText(String.valueOf(finalfloat));
//
// }
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
if (!mBottomSheetDialog.isShowing()){
counter = 1;
}
//
mBottomSheetDialog.show();
}
});
return rowView;
}
I tried using boolean but it didn't go as well as i expected.
I will appreciate any help!
Is all of your code (the getView() method) within your ArrayAdapter class? If so, move you listener register out into your Activity, and then the listener needs only pull the required value from the selected item and append it to a property of your Activity class, and then raise the view to show the running total.
I have a problem using folding cell library from the RAMOTION
I have implemented everything but I am facing a problem with the list view
I have a list of planets and when user tap on let's say Jupiter the view gets unfolded and more information is visible to the user and when user tap on the same view which is seeing then the view gets folded
Problem
if the user scrolls down the list and then scroll back up and come back up to Jupiter the view remains unfolded and it is happening to all the view.
I appreciate if anyone helps me out
folding state
here
unfolding state
here
AdapterClass
#SuppressWarnings({"WeakerAccess", "unused"})
public class SolarSystemFoldingCellListAdapter extends ArrayAdapter<SolarSystemItemFoldingCell> {
private HashSet<Integer> unfoldedIndexes = new HashSet<>();
private View.OnClickListener defaultRequestBtnClickListener;
private int incomingPosition ;
public SolarSystemFoldingCellListAdapter(Context context, List<SolarSystemItemFoldingCell> objects) {
super(context, 0, objects);
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
// get item for selected view
SolarSystemItemFoldingCell solarSystemItemFoldingCell = getItem(position);
// if cell is exists - reuse it, if not - create the new one from resource
FoldingCell cell = (FoldingCell) convertView;
final ViewHolder viewHolder;
if (cell == null) {
viewHolder = new ViewHolder();
LayoutInflater vi = LayoutInflater.from(getContext());
cell = (FoldingCell) vi.inflate(R.layout.solar_system_folding_cell, parent, false);
// binding view parts to view holder
viewHolder.foldingCell = cell.findViewById(R.id.folding_cell);
viewHolder.relativeLayoutFolded = cell.findViewById(R.id.relativeLayoutFolded);
viewHolder.linearLayoutFolded = cell.findViewById(R.id.linearLayoutFolded);
viewHolder.planetOrStarNameFolded = cell.findViewById(R.id.planetOrStarNameFolded);
viewHolder.mass = cell.findViewById(R.id.mass);
viewHolder.actualMass = cell.findViewById(R.id.actualMass);
viewHolder.distance = cell.findViewById(R.id.distance);
viewHolder.actualDistance = cell.findViewById(R.id.actualDistance);
viewHolder.diameter = cell.findViewById(R.id.diameter);
viewHolder.actualDiameter = cell.findViewById(R.id.actualDiameter);
viewHolder.speed = cell.findViewById(R.id.speed);
viewHolder.actualSpeed = cell.findViewById(R.id.actualSpeed);
viewHolder.moreInfoButton = cell.findViewById(R.id.button);
viewHolder.frameLayoutUnfolded = cell.findViewById(R.id.frameLayoutUnfolded);
viewHolder.planetOrStarNameUnfolded = cell.findViewById(R.id.planetOrStarNameUnfolded);
cell.setTag(viewHolder);
} else {
// for existing cell set valid valid state(without animation)
if (unfoldedIndexes.contains(position)) {
cell.unfold(true);
} else {
cell.fold(true);
}
viewHolder = (ViewHolder) cell.getTag();
}
if (null == solarSystemItemFoldingCell)
return cell;
// bind data from selected element to view through view holder
viewHolder.planetOrStarNameFolded.setText(solarSystemItemFoldingCell.getPlantOrStarNameFolded());
viewHolder.actualMass.setText(solarSystemItemFoldingCell.getActualMass());
viewHolder.actualDistance.setText(solarSystemItemFoldingCell.getActualDistance());
viewHolder.actualDiameter.setText(solarSystemItemFoldingCell.getActualDiameter());
viewHolder.actualSpeed.setText(solarSystemItemFoldingCell.getActualSpeed());
viewHolder.planetOrStarNameUnfolded.setText(String.valueOf(solarSystemItemFoldingCell.getPlanetOrStarNameUnfolded()));
//setting Fonts
viewHolder.planetOrStarNameFolded.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.mass.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.distance.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.diameter.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.speed.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.actualMass.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualDistance.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualDiameter.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualSpeed.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.moreInfoButton.setTypeface(App.getAppInstance().getArvoRegular());
// set custom btn handler for list item from that item
if (solarSystemItemFoldingCell.getRequestBtnClickListener() != null) {
viewHolder.moreInfoButton.setOnClickListener(solarSystemItemFoldingCell.getRequestBtnClickListener());
} else {
// (optionally) add "default" handler if no handler found in item
viewHolder.moreInfoButton.setOnClickListener(defaultRequestBtnClickListener);
}
viewHolder.relativeLayoutFolded.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Something gets clicked", Toast.LENGTH_SHORT).show();
viewHolder.foldingCell.fold(false);
registerFold(incomingPosition);
}
});
return cell;
}
// simple methods for register cell state changes
public void registerToggle(int position) {
if (unfoldedIndexes.contains(position)) {
registerFold(position);
incomingPosition = position;
}else
registerUnfold(position);
}
public void registerFold(int position) {
unfoldedIndexes.remove(position);
}
public void registerUnfold(int position) {
unfoldedIndexes.add(position);
}
public View.OnClickListener getDefaultRequestBtnClickListener() {
return defaultRequestBtnClickListener;
}
public void setDefaultRequestBtnClickListener(View.OnClickListener defaultRequestBtnClickListener) {
this.defaultRequestBtnClickListener = defaultRequestBtnClickListener;
}
// View lookup cache
private static class ViewHolder {
RelativeLayout relativeLayoutFolded ;
LinearLayout linearLayoutFolded ;
TextView planetOrStarNameFolded;
TextView mass;
TextView actualMass;
TextView distance;
TextView actualDistance;
TextView diameter;
TextView actualDiameter;
TextView speed;
TextView actualSpeed ;
Button moreInfoButton ;
FrameLayout frameLayoutUnfolded ;
TextView planetOrStarNameUnfolded;
FoldingCell foldingCell ;
}
}
SolarSystemClass
private void listViewIntegration (){
arrayList = addingDataIntoList();
solarSystemFoldingCellListAdapter = new SolarSystemFoldingCellListAdapter(SolarSystem.this , arrayList);
listView.setAdapter(solarSystemFoldingCellListAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int duration = 500; //miliseconds
int offset = 0; //fromListTop
listView.smoothScrollToPositionFromTop(position,offset,duration);
// toggle clicked cell state
((FoldingCell) view).toggle(false);
// register in adapter that state for selected cell is toggled
solarSystemFoldingCellListAdapter.registerToggle(position);
// listView.smoothScrollToPosition(position);
}
});
}
I wanted to show the image only at the selected row from listview. Here is the code:
private class ListAdapter extends BaseAdapter {
LayoutInflater inflater;
ViewHolder viewHolder;
public ListAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public int getCount() {
return attendeeList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.attendee_listview_row,
null);
viewHolder = new ViewHolder();
viewHolder.txt_dName = (TextView) convertView
.findViewById(R.id.txtDisplayName);
viewHolder.txt_dAddr = (TextView) convertView
.findViewById(R.id.txtDisplayAddr);
viewHolder.txt_dtelNo = (TextView) convertView
.findViewById(R.id.txtDisplayTelNo);
viewHolder.btn_scan = (ImageView) convertView.findViewById(R.id.btnScan);
viewHolder.registered_tag = (ImageView) convertView.findViewById(R.id.ivRegisteredTag);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_dName.setText(attendeeList.get(position)
.getAccountName().trim());
viewHolder.txt_dAddr.setText(attendeeList.get(position)
.getAttendeeAddr().trim());
viewHolder.txt_dtelNo.setText("Tel no: "
+ attendeeList.get(position).getTelNo().trim());
viewHolder.btn_scan.setOnClickListener(new OnClickListener(){
public void onClick(View v){
viewHolder.registered_tag.setVisibility(View.VISIBLE);
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
});
return convertView;
}
}
With these code, I am trying to show the registered_tag upon btn_scan onClick. However, the image is not really showing at the selected row. It shows at other row instead.
Any ideas? Thanks in advance.
Probably you are getting last row image change when clicking on any row because viewHolder will contain last row view when getView called. Use setTag and getTag method of viewHolder.btn_scan view to save and get selected row view in onClick method:
viewHolder.btn_scan.setTag(viewHolder);
viewHolder.btn_scan.setOnClickListener(new OnClickListener(){
public void onClick(View v){
ViewHolder selectedViewHolder=(ViewHolder)v.getTag();
selectedViewHolder.registered_tag.setVisibility(View.VISIBLE);
...
}
});
I have an array of image urls and I want to download the images using Picasso and show them in a grid view. My current implementation works but it is putting the last image into every image view in the grid view.
public class GridViewAdapter extends ArrayAdapter {
Context context;
public GridViewAdapter(Context context) {
super(context, 0);
this.context = context;
}
public int getCount() {
return thumbnailURLS.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.grid_row, parent, false);
ImageView gridImageView = (ImageView)row.findViewById(R.id.gridImageView);
for(String s : thumbnailURLS) {
Picasso.with(context)
.load(s)
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(gridImageView);
}
}
return row;
}
}
getView is called once for each item (ie the number of times it is called is equal to 'getCount'). Easiest thing to do would be to ditch the for loop and lookup the thumbnailUrl using the position argument.
ie
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.grid_row, parent, false);
}
ImageView gridImageView = (ImageView) row.findViewById(R.id.gridImageView);
Picasso.with(context)
.load(thumbnailURLs.get(position))
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(gridImageView);
return row;
}
Your getView is actually loading every single image into the list item, and so only the last one becomes the visible one!
The correct solution would be as follows:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(R.layout.grid_row, parent, false);
}
ImageView gridImageView = (ImageView) row.findViewById(R.id.gridImageView);
Picasso.with(context).load(thumbnailURLS.get(position)).placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder).into(gridImageView);
return row;
}
You should also look into using the ViewHolder pattern (http://developer.android.com/training/improving-layouts/smooth-scrolling.html#ViewHolder) such that you are not doing a findViewById every time getView is being called!
try this
// Get the image URL for the current position.
String url = getItem(position);
// Trigger the download of the URL asynchronously into the image view.
Picasso.with(context) //
.load(url) //
.placeholder(R.drawable.placeholder) //
.error(R.drawable.error) //
.fit() //
.into(view);
Is it possible to get an item view based on its position in the adapter and not in the visible views in the ListView?
I am aware of functions like getChildAt() and getItemIdAtPosition() however they provide information based on the visible views inside ListView. I am also aware that Android recycles views which means that I can only work with the visible views in the ListView.
My objective is to have a universal identifier for each item since I am using CursorAdapter so I don't have to calculate the item's position relative to the visible items.
Here's how I accomplished this. Within my (custom) adapter class:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(textViewResourceId, parent, false);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.name = (TextView) view.findViewById(R.id.name);
viewHolder.button = (ImageButton) view.findViewById(R.id.button);
viewHolder.button.setOnClickListener
(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = (int) viewHolder.button.getTag();
Log.d(TAG, "Position is: " +position);
}
});
view.setTag(viewHolder);
viewHolder.button.setTag(items.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).button.setTag(items.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
return view;
}
Essentially the trick is to set and retrieve the position index via the setTag and getTag methods. The items variable refers to the ArrayList containing my custom (adapter) objects.
Also see this tutorial for in-depth examples. Let me know if you need me to clarify anything.
See below code:
public static class ViewHolder
{
public TextView nm;
public TextView tnm;
public TextView tr;
public TextView re;
public TextView membercount;
public TextView membernm;
public TextView email;
public TextView phone;
public ImageView ii;
}
class ImageAdapter extends ArrayAdapter<CoordinatorData>
{
private ArrayList<CoordinatorData> items;
public FoodDriveImageLoader imageLoader;
public ImageAdapter(Context context, int textViewResourceId,ArrayList<CoordinatorData> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
ViewHolder holder = null;
if (v == null)
{
try
{
holder=new ViewHolder();
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new FoodDriveImageLoader(FoodDriveModule.this);
v = vi.inflate(R.layout.virtual_food_drive_row, null);
//System.out.println("layout is null.......");
holder.nm = (TextView) v.findViewById(R.id.name);
holder.tnm = (TextView) v.findViewById(R.id.teamname);
holder.tr = (TextView) v.findViewById(R.id.target);
holder.re = (TextView) v.findViewById(R.id.received);
holder.membercount = new TextView(FoodDriveModule.this);
holder.membernm = new TextView(FoodDriveModule.this);
holder.email = new TextView(FoodDriveModule.this);
holder.phone = new TextView(FoodDriveModule.this);
holder.ii = (ImageView) v.findViewById(R.id.icon);
v.setTag(holder);
}
catch(Exception e)
{
System.out.println("Excption Caught"+e);
}
}
else
{
holder=(ViewHolder)v.getTag();
}
CoordinatorData co = items.get(position);
holder.nm.setText(co.getName());
holder.tnm.setText(co.getTeamName());
holder.tr.setText(co.getTarget());
holder.re.setText(co.getReceived());
holder.ii.setTag(co.getImage());
imageLoader.DisplayImage(co.getImage(), FoodDriveModule.this , holder.ii);
if (co != null)
{
}
return v;
}
}
A better option is to identify using the data returned by the CursorAdapter rather than visible views.
For example if your data is in a Array , each data item has a unique index.
Here, Its very short described code, you can simple re-use viewholder pattern to increase listview performance
Write below code in your getview() method
ViewHolder holder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.skateparklist, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView
.findViewById(R.id.textView1);
holder.DistanceView = (TextView) convertView
.findViewById(R.id.textView2);
holder.imgview = (NetworkImageView) convertView
.findViewById(R.id.imgSkatepark);
convertView.setTag(holder); //PLEASE PASS HOLDER AS OBJECT PARAM , CAUSE YOU CAN NOY PASS POSITION IT WILL BE CONFLICT Holder and Integer can not cast
//BECAUSE WE NEED TO REUSE CREATED HOLDER
} else {
holder = (ViewHolder) convertView.getTag();
}
// your controls/UI setup
holder.DistanceView.setText(strDistance);
......
return convertview
Listview lv = (ListView) findViewById(R.id.previewlist);
final BaseAdapter adapter = new PreviewAdapter(this, name, age);
confirm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
View view = null;
String value;
for (int i = 0; i < adapter.getCount(); i++) {
view = adapter.getView(i, view, lv);
Textview et = (TextView) view.findViewById(R.id.passfare);
value=et.getText().toString();
Toast.makeText(getApplicationContext(), value,
Toast.LENGTH_SHORT).show();
}
}
});