如何在一行ListView中更改ImageView?
问题描述:
我有一个使用SimpleCursorAdapter填充的ListView。下面的一行布局给出:如何在一行ListView中更改ImageView?
<?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;
}
我能够阅读列表视图中的内容,但不能改变他们..请帮助:)
答
您需要重写此列表视图的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....
通过BaseAdapter延伸适配器类,并定义在Holder类的TextView和ImageView的,由holder.textview =(TextView的)convertView.findViewById(R.id.txt1)访问它们;和getView()函数 – AkashG 2012-07-10 07:00:22
谢谢imageview相同。以及我只是扩展了CorsorAdapter类并且重写了bindview方法..它现在工作完美无缺:) – 2012-07-11 05:45:28