【问题标题】:Android setting images inside listViewAndroid在listView中设置图片
【发布时间】:2012-05-10 13:43:15
【问题描述】:

所以我有这个列表视图和我为它制作的自定义 XML 文件。

在文件中,有一个没有源集的图像具有固定的 id。

我想将此图像源更改为可绘制文件夹中的资源之一。

这是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout 
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView 
 android:id="@+id/listImage"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:contentDescription="protection image"
 android:layout_marginTop="10dp"
/>
<LinearLayout 
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="10dp"
>
<TextView android:id="@+id/text1" 
android:textSize="20dp"  
android:textStyle="bold"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<TextView android:id="@+id/text2"
android:textSize="12dp" 
android:layout_marginTop="5dp"
android:layout_width="wrap_content" 
android:layout_height="fill_parent"/>
</LinearLayout>
</LinearLayout>

</LinearLayout>

这是我迄今为止尝试过的,但它崩溃了:

        adapter=new SimpleAdapter(this, listItems, R.layout.custom_row_view,new String[]{"name", "current"},  new int[] {R.id.text1, R.id.text2});
    ImageView img;
    img = (ImageView) findViewById(R.id.listImage);
    Drawable d = getResources().getDrawable(R.drawable.opened);
    img.setImageDrawable(d);
    setListAdapter(adapter);

【问题讨论】:

  • 你想为所有列表项设置相同的图像还是为每个列表项设置不同的图像?
  • 我有两张图片,我需要决定哪些物品得到什么图片
  • 你有什么条件来决定列表项的图像?
  • 不在这里,条件是一个简单的 if 语句。我还没有这样做,因为我想看看设置图像是否有效!

标签: android image listview bitmap drawable


【解决方案1】:
ImageView img;
    img = (ImageView) findViewById(R.id.listImage);

这意味着您指的是布局中存在的对象,您可以将其用于 Activity 的 setContentView()。但您的 ImageView 不存在于该布局中。

在这里,您尝试使用 ListView 来引用它。所以很明显你得到了空指针异常。

您还必须使用自定义适配器。尝试以下链接中的一个。

http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter

http://www.mkyong.com/android/android-listview-example/

【讨论】:

  • 我不确定我是否理解这些示例。如果我有 id,是否有任何简单的方法可以更改图像?
  • 没有。自定义列表视图不可能。您只能使用自定义适配器。
  • 好吧,但我的列表视图有两行。是否也可以适应这个?
  • 是的,使用自定义列表视图一切皆有可能。试一试。我不能这么简单。
  • 但我不知道如何用两行来做到这一点。有什么例子吗?
猜你喜欢
  • 1970-01-01
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 2018-07-31
  • 2013-08-30
相关资源
最近更新 更多