public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {
// new method
private ListView listView;
private AsyncImageLoader asyncImageLoader;
private ImageAndText imageAndText;
//constructor
public ImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts) {
super(activity, 0, imageAndTexts);
asyncImageLoader = new AsyncImageLoader();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Activity activity = (Activity) getContext();
////////////////////////////////////////////////////////////////////////////////////////////////
// Load the image and set it on the ImageView
//new method
// Inflate the views from XML
View rowView = convertView;
ViewCache viewCache;
if (rowView == null) {
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(R.layout.image_and_text_row, null);
viewCache = new ViewCache(rowView);
rowView.setTag(viewCache);
} else {
viewCache = (ViewCache) rowView.getTag();
}
imageAndText = getItem(position);
Button btn2=(Button) findViewById(R.id.button1);
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//...........
}
});
This adapter is for the ListView, and it takes the image_and_text_row.xml which represent the row data of the listview. The program crashed when I set a click listener to the btn2. If the listener is deleted then the program runs fine.
the question is why the adapter cannot have a button click listener inside the code?
Just a shot in the dark: but your line
Button btn2=(Button) findViewById(R.id.button1);refers to the ListActivity or ListView that the adapter is in. Therefore,R.id.button1does not exist…Have you tried:
Button btn2=((Button)rowView.findViewById(R.id.button1));This may be your issue (without being able to see your logcat, that is).findViewById()finds children. The original statement would look for the child of the Activity or View. This new statement would find the child of the rowView.Of course, this is an assumption, as since you have not described the application or problem completely, I must assume according to the information that we do have that there is a button for every row.
Hope this helps,
FuzzicalLogic
P.S. Hope you caught the hint that you will get shoddy answers like this one if there is a lack of pertinent information. A good guide is: 1) What is happening? 2) What do you expect to happen? 3) What do your debugging resources indicate? 4) What supplemental research or concepts do we need to know? These lead to longer questions, but they are certainly more effective and so are the answers that result from them.