尝试在列表活动中更改ImageView

时间:2012-10-11 16:16:49

标签: android image listview drawable

当我尝试在列表视图中更改图像时遇到问题。

下面是列表中行的布局XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:orientation="horizontal" 
android:gravity="left">


<ImageView
    android:id="@+id/flagIcon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_weight="0.1"
    android:src="@drawable/orange_flag"/>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:gravity="center_vertical"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/location_row_item_main_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/location_row_item_secondary_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" 
        android:textAppearance="?android:attr/textAppearanceSmall"/>

</LinearLayout>

运行正常并显示drawable声明(即orange_flag),但当我尝试在以下代码中更改它时,这不会改变:

private class MyListAdapter extends ResourceCursorAdapter { 

    // In your ListActivity class, create a new inner class that extends ResourceCursorAdapter. 
    //This inner class is the custom CursorAdapter we will use to manage how data is bound to a list item:

    public MyListAdapter(Context context, Cursor cursor) { 
        super(context, R.layout.row_location, cursor);
    } 

    @Override
    public void bindView(View view, Context context, Cursor cursor) { 
        TextView title = (TextView) view.findViewById(R.id.location_row_item_main_text);
        title.setText(cursor.getString(
                cursor.getColumnIndex(RMDbAdapter.RACKING_SYSTEM)));
        ImageView flagIcon = (ImageView) view.findViewById(R.id.flagIcon);
        String risk = cursor.getString(cursor.getColumnIndex(RMDbAdapter.RISK));
        if (risk == "Red Risk"){
            flagIcon.setImageResource(R.drawable.red_flag);
        }
        else if (risk == "Green Risk"){
            flagIcon.setImageResource(R.drawable.green_flag);
        }
        else if (risk =="No Risk"){
            flagIcon.setImageResource(R.drawable.note);
        }

有什么想法吗?!

3 个答案:

答案 0 :(得分:1)

在比较内容的字符串数据类型时,始终使用equals()equalsIgnoreCase()

对于java中的字符串:

  • ==比较字符串是否与相同的对象
  • equals()比较字符串是否具有相同的字符序列

答案 1 :(得分:0)

尝试在设置资源后添加flagIcon.invalidate()

答案 2 :(得分:0)

而不是尝试

flagIcon.setImageResource(R.drawable.red_flag);

你可以试试这个:

flagIcon.setBackgroundResource(R.drawable.red_flag);