我有以下情况.
我有一个ListView,ListView的每个项目都包含不同的小部件(TextViews,ImageViews等...),这些小部件getView()在自定义适配器的方法中从一个布局中膨胀.
现在,我想实现以下目标:
当某个事件被触发时,我想要更改项目内的视图的背景.
请问我该怎么办?
这是项目布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cardlayout"
android:layout_width="320dp"
android:layout_height="130dp"
android:background="@android:color/transparent"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp" >
<FrameLayout
android:layout_width="320dp"
android:layout_height="117dp" >
<View
android:id="@+id/card"
android:layout_width="320dp"
android:layout_height="117dp"
android:background="@drawable/card_selector" />
</FrameLayout>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
我需要改变背景 card
我试过这样做:
View v=lv.getAdapter().getView(index, null, lv);
View card =(View)v.findViewById(R.id.card);
card.setBackgroundResource(R.drawable.pressed_background_card);
Run Code Online (Sandbox Code Playgroud)
但没有成功: - ((
小智 7
当您的事件被触发时,您应该只在适配器上调用notifyDataSetChanged,以便它将再次调用所有可见元素的getView.
你的getView方法应该考虑到一些元素可能有不同的背景颜色(如果元素不需要更改背景,不要忘记将其设置为正常颜色,否则回收时,滚动时会有许多元素具有更改的背景)
编辑:
我会尝试这样的事情:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.card, parent, false);
}
//This part should also be optimised with a ViewHolder
//because findViewById is a costly operation, but that's not the point of this example
CardView cardView =(CardView)convertView .findViewById(R.id.card);
//I suppose your card should be determined by your adapter, not a new one each time
Card card = getItem(position);
//here you should check sthg like the position presence in a map or a special state of your card object
if(mapCardWithSpecialBackground.contains(position))
{
card.setBackgroundResource(specialBackground);
}
else
{
card.setBackgroundResource(normalBackground);
}
cardView.setCard(card);
return convertView;
}
Run Code Online (Sandbox Code Playgroud)
在特殊事件中,我会将项目的位置添加到地图中并调用notifyDataSetChanged.