使用自定义适配器单击ListView

时间:2012-11-10 22:50:55

标签: android android-listview custom-adapter

我正在开发一个Android应用程序,它从互联网上检索一些图像并将它们放在ListView上。单击其中一个图像时,将创建另一个活动,其中包含有关图像的一些详细信息。问题是我无法跟踪列表中的点击次数。

Activity.java

public class MyActivity extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        // List<FlickerPicture> pictures = ...
        ListView listView = (ListView) findViewById(android.R.id.list);
        listView.setOnItemClickListener(new OnItemClickListener() {
             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                 Log.d("MyActivity", "You clicked on " + arg2);
                 Toast.makeText(getBaseContext(), "You clicked on " + arg2,
                 Toast.LENGTH_LONG).show();
             }
         });
        ArrayAdapter<FlickerPicture> adapter = new FlickrItemAdapter(this, pictures);
        listView.setAdapter(adapter);
    }
}

FlickrItemAdapter

public class FlickrItemAdapter extends ArrayAdapter<FlickerPicture> {
    public FlickrItemAdapter(Activity activity, List<FlickerPicture> pictures) {
        super(activity, 0, pictures);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Activity activity = (Activity) getContext();
        LayoutInflater inflater = activity.getLayoutInflater();
        // Inflate the views from XML
        View rowView = inflater.inflate(R.layout.miniature_layout, null);
        FlickerPicture picture = getItem(position);
        // Load the image and set it on the ImageView
        ImageButton imageButton = (ImageButton) rowView.findViewById(R.id.miniature_picture);
        try {
            imageButton.setImageBitmap(Util.loadBitmap(picture.getMiniatureLink()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rowView;
    }
}

问题

如何使列表中的图像“可点击”?

1 个答案:

答案 0 :(得分:1)

您使用的是ImageButton而不是ImageView。只需更改miniature_layout.xml和适配器的getView()即可使用ImageView,因为ImageButton正在使用Click事件来阻止它到达ListView。