将图像设置为列出视图项目onclick

时间:2014-07-26 07:56:56

标签: android image listview

我是Android应用程序开发的初学者。我今天正在浏览listview。有一点疑问,比方说,我有一个填充了字符串数据的列表视图。现在,当我单击列表视图项时,它应该将图像设置到该特定行中文本视图的一侧。可能吗 ?请帮帮我。非常感谢代码片段或教程链接!在这个论坛上提前感谢所有这些天才开发者。

2 个答案:

答案 0 :(得分:0)

这是可能的。首先,您需要使用和适配器来扩展自定义ListView项目布局。

布局看起来像这样:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
    <ImageView
        android:id="@+id/itemImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/itemText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/itemImage"/>
</RelativeLayout>

然后,对于您的列表,您将注册一个OnItemClickListener,如下所示:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ImageView image = (ImageView) view.findViewById(R.id.itemImage);
        try {
            // Open the image as an InputStream
            InputStream input = getAssets().open("image.jpg");
            // Transform the stream to a Bitmap and set it to the ImageView
            image.setImageBitmap(BitmapFactory.decodeStream(input));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});

请注意,侦听器会收到可用于打开和设置特定图像的位置(此示例对列表中的所有项目使用1个图像)。

答案 1 :(得分:0)

当然这是可能的。你应该做到以下几点:
1.你需要为你的listView行定义一个布局文件,它应该包括一个Imageview和一个TextView。
2.在Adapter类的getView方法中,需要在步骤1中膨胀布局文件,并将ImageView设置为不可见。 3.在onItemClicked函数中,您应该将ImageView设置为可见 希望这有帮助。

相关问题