I have list view that populated its items based on a list of names. I've added an adapter to the list view and set items. Here's the code:
items = new String[]{ "Apple", "Banana" };
list = (ListView)findViewById(R.id.fruits_listView);
list.setAdapter(new ArrayAdapter<String>(this, R.layout.list_fruits, R.id.list_fruits_textView, items) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
ImageView imageView = (ImageView)v.findViewById(R.id.list_fruits_imageView);
// Change icon based on name and set click listener for it
String s = items[position];
if (s.equals("Apple"))
{
imageView.setImageResource(R.drawable.apple);
imageView.setOnClickListener(appleListener);
}
else if (s.equals("Banana"))
{
imageView.setImageResource(R.drawable.banana);
imageView.setOnClickListener(bananaListener);
}
return v;
}
});
// Setup listeners
appleListener = new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(this, Apple.class));
}
};
bananaListener = new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(this, Banana.class));
}
};
However when I click the list items nothing happens, seems listeners don't work. Any idea what my problem is?
It's simple, just initialize your listeners before setting the adapters.
I hope this solves your problem.
Set these properties in your ListView
android:focusable="false"
android:focusableInTouchMode="false"
android:descendantFocusability="blocksDescendants"
Also make your ImageView(s)
clickable:
yourImageViewObject.setClickable(true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.