我有一个ListActivity,在我的列表中,我有高度复杂的listitems,包含多个ImagesViews TextViews和Buttons。当我单击一个按钮时,我想编辑一些文本视图并更改一些背景颜色。我的实现工作,但只有当我点击的按钮在第一行可见时。我正在使用getChildAt()
抓取其中一条可见行,但我需要知道要抓哪一行。
public void onClick(View v){
System.out.println("Something got clicked");
if(v.getId() == R.id.lovebutton){
MainListItem i = mainAdapter.getItem(listView.getFirstVisiblePosition());
i.loved=true;
i.loves++;
View view;
view = listView.getChildAt(0);
//view = listView.getChildAt(1);
((TextView) view.findViewById(R.id.lovecount)).setText(String.valueOf(i.loves));
view.findViewById(R.id.lovebutton).setBackgroundColor(Color.parseColor(i.brandLoveColor));
((ImageView)view.findViewById(R.id.lovebutton)).setImageResource(R.drawable.lovewhite);
}}
答案 0 :(得分:2)
有很多方法可以做到这一点。保存pojo中的状态,在onClick中更新它们并调用#notifyDataSetChanged()
。
或者,
您可以将位置作为标记添加到适配器的getView中的按钮。在OnClick中,您可以获取标记。这样您就可以知道按钮属于哪个位置。
在Joe的帮助下 - Android: Access child views from a ListView
public void onClick(View v){
System.out.println("Something got clicked");
if(v.getId() == R.id.lovebutton){
int wantedPosition = Integer.parseInt(view.getTag());
int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0
int wantedChild = wantedPosition - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
return;
}
// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.
View wantedView = listView.getChildAt(wantedChild);
MainListItem i = mainAdapter.getItem(wantedPosition);
i.loved=true;
i.loves++;
((TextView) view.findViewById(R.id.lovecount)).setText(String.valueOf(i.loves));
view.findViewById(R.id.lovebutton).setBackgroundColor(Color.parseColor(i.brandLoveColor));
((ImageView)view.findViewById(R.id.lovebutton)).setImageResource(R.drawable.lovewhite);
}
}
答案 1 :(得分:1)
在listView中获取单击的行,您必须使用“OnItemClickListener”。
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(pos);
System.out.println(pos);//This will return your position
}
});