【发布时间】:2015-11-03 12:59:22
【问题描述】:
我对 Android 很陌生。我正在使用一个列表视图,它使用自定义 list_v.xml 来容纳 x2 文本视图。我还包含了一个我想通过活动更新的 imageView。
<?xml version="1.0" encoding="utf-8"?>
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:maxHeight="40sp"
android:textColor="#FFFFFF" />
<TextView
android:id="@+id/body"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:maxHeight="35sp"
android:textColor="#FFFFFF" />
我已经使用这个简单的适配器概念通过 Json 更新了 textview,但我想将每一行的 imageView 设置为相同。我可以将drawable硬编码到上面的xml中,但如果有意义的话,我想重用这个视图并为其他视图更新图像。
这是我更新 textViews 的活动类,但如何以编程方式更新 imageView 以对所有行使用相同的图像。
imageView src 不会来自我的 Json 请求,它将是包中的可绘制对象。
@Override
protected void onPostExecute(JSONArray json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
// Storing JSON item in a Variable
String cat = "Category: " + c.getString(TAG_Cat);
String title = c.getString(TAG_Title);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Cat, cat);
map.put(TAG_Title, title);
oslist.add(map);
listView = (ListView)findViewById(R.id.listView);
ListAdapter adapter = new SimpleAdapter(TopTipsActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_Cat,TAG_Title},
new int[] {R.id.title,R.id.body});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(TopTipsActivity.this, "You Clicked at "+oslist.get(+position).get("Title"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
我试过用
ImageView image = (ImageView) listView.findViewById(R.id.icon);
image.setBackgroundResource(R.drawable.tip_selected);
我猜我需要以某种方式引用 list_v 而不是 listView.findViewById。我可能完全没有抓住重点。
【问题讨论】:
-
是的,您需要访问列表的每一行/元素,然后从中找到 ImageView。所以基本上你应该使用扩展 BaseAdapter 的自定义适配器类。
标签: java android xml android-listview simpleadapter