如何在ListView的行中更改ImageView?

时间:2012-07-10 06:36:14

标签: java android android-listview

我有一个使用SimpleCursorAdapter填充的ListView。行布局如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <TextView 
        android:id="@+id/row" 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dp" />

    <ImageView
        android:id="@+id/enable_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:padding="10dp"
        android:contentDescription="@string/image_description"
        android:src="@android:drawable/checkbox_off_background" />

</RelativeLayout>

我想要做的是在创建活动时根据某些共享首选项将imageview的源更改为其他内容。这是我使用的代码,但它不起作用:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    long appliedProfileId = prefs.getLong("appliedProfileId", -1); 

    if(appliedProfileId != -1) {
        /*View rowView = (View) getListView().getAdapter().getView(info.psition, null, null);
        TextView textView = (TextView) rowView.findViewById(R.id.row);*/
        ListView listView = getListView();
        ListAdapter adapter = listView.getAdapter();
        View appliedRowLayout = (View) adapter.getView(getItemPositionByAdapterId(adapter, appliedProfileId), null, null);

        TextView textView = (TextView) appliedRowLayout.findViewById(R.id.row);
        Log.d("asdasd", textView.getText().toString());
        ImageView imageView = (ImageView) appliedRowLayout.findViewById(R.id.enable_image);
        imageView.setImageResource(android.R.drawable.checkbox_on_background);
        setListAdapter(adapter);
    }

这是getItemPositionByAdapterId方法:

private int getItemPositionByAdapterId(ListAdapter adapter, final long id)
{
    for (int i = 0; i < adapter.getCount(); i++)
    {
        if (adapter.getItemId(i) == id)
            return i;
    }
    return -1;
}

我能够阅读listview的内容,但无法更改它们。请帮助:)

1 个答案:

答案 0 :(得分:0)

您需要覆盖此listview的getView方法。查看Customizing Android ListView Items

你需要做这样的事情。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position == 0) // first element in the list
 {
   convertView.findViewById(R.id.image1).setImageURI(....)
 }
    and so on....