简体   繁体   中英

How to change an ImageView in a row of ListView?

I have a ListView which is populated using a SimpleCursorAdapter. The row layout is given below:

<?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>

What i want to do is to change the source of the imageview to something else based on some shared preference when the activity is created. This is the code that i use but it doesn't work:

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);
    }

This is the getItemPositionByAdapterId method:

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;
}

I am able to read the contents of the listview but cannot change them.. Pleas help :)

You need to override the getView method for this listview. Check Customizing Android ListView Items

You need to do something like this.

@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....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM