Say I have 5 items in my list. If I long press an item, a toast message appears giving the position I pressed which is correct, but I have an ImageView
that I want to make visible once I long press an item at that position. The problem is that the ImageView
is always appearing at the bottom of the list and not the position I selected. Here's my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(Html.fromHtml("<small>" + GalleryActivity.item + "</small>"));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
listOfImages = (ListView) findViewById(R.id.listOfImages);
customAdaptor = new CustomAdaptor();
listOfImages.setAdapter(customAdaptor);
listOfImages.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ImageActivity.this, "You pressed at position " + position, Toast.LENGTH_SHORT).show();
delete.setClickable(true);
delete.setVisibility(View.VISIBLE);
return true;
}
});
}
class CustomAdaptor extends BaseAdapter {
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final View view = getLayoutInflater().inflate(R.layout.custom_layout, null);
imageView = (ImageView) view.findViewById(R.id.customImage);
delete = (ImageView) view.findViewById(R.id.delete);
test = (TextView) view.findViewById(R.id.test);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
loadImageFromUrl(images.get(position));
return view;
}
}
The object delete
does not contain the current position image because you do not tell him to do so. delete
contains the last things you affect to him -> the last image of the list.
You need inside your listener to get the right image, then to make it visible
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ImageActivity.this, "You pressed at position " + position, Toast.LENGTH_SHORT).show();
delete = view.findViewById(R.id.delete); //select the right image
delete.setClickable(true);
delete.setVisibility(View.VISIBLE);
return true;
}
});