java – 更改ListView背景 – 奇怪的行为
作者:互联网
我在更改ListView中的视图背景时遇到问题.
我需要的:
在onClick()上更改行的背景图像
实际发生了什么:
在按下例如后,背景被改变(选择)第一个条目.但在向下滚动后,也会选择第8个条目.
滚动回到顶部,第一个不再被选中.现在选择第二个条目.
继续滚动,继续跳…
我在代码中的内容:
我有通道,onClick()我切换选择的通道布尔值的属性
然后我改变了背景.
我只是在onClick()这样做,这就是为什么我不明白为什么它也会在其他条目上发生.
我注意到的一件事是:它似乎只是“绘图” – 部分,因为“通过它自己”选择的项目仍然是假的选定值
我认为它似乎与自定义ListAdapters getView(…)中的视图重用有关
ListActivity中的onClick()代码:
@Override
protected ViewHolder createHolder(View v) {
// createHolder will be called only as long, as the ListView is not
// filled
TextView title = (TextView) v
.findViewById(R.id.tv_title_channel_list_adapter);
TextView content = (TextView) v
.findViewById(R.id.tv_content_channel_list_adapter);
ImageView icon = (ImageView) v
.findViewById(R.id.icon_channel_list_adapter);
if (title == null || content == null || icon == null) {
Log.e("ERROR on findViewById",
"Couldn't find Title, Content or Icon");
}
ViewHolder mvh = new MyViewHolder(title, content, icon);
// We make the views become clickable
// so, it is not necessary to use the android:clickable attribute in
// XML
v.setOnClickListener(new ChannelListAdapter.OnClickListener(mvh) {
public void onClick(View v, ViewHolder viewHolder) {
// we toggle the enabled state and also switch the the
// background
MyViewHolder mvh = (MyViewHolder) viewHolder;
Channel ch = (Channel) mvh.data;
ch.setSelected(!ch.getSelected()); // toggle
if (ch.getSelected()) {
v.setBackgroundResource(R.drawable.row_blue_selected);
} else {
v.setBackgroundResource(R.drawable.row_blue);
}
// TESTING
Log.d("onClick() Channel", "onClick() Channel: "
+ ch.getTitle() + " selected: " + ch.getSelected());
}
});
return mvh;
}
getView代码(…):
@Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
// When view is not null, we can reuse it directly, there is no need
// to reinflate it.
// We only inflate a new View when the view supplied by ListView is
// null.
if (view == null) {
view = mInflater.inflate(mViewId, null);
// call own implementation
holder = createHolder(view);
// TEST
// we set the holder as tag
view.setTag(holder);
} else {
// get holder back...much faster than inflate
holder = (ViewHolder) view.getTag();
}
// we must update the object's reference
holder.data = getItem(position);
// <EDIT SOLUTION>
if(getItem(position).get_id() == channelList.get(position).get_id()){
if(getItem(position).getSelected())
{
view.setBackgroundResource(R.drawable.row_blue_selected);
}
else{
view.setBackgroundResource(R.drawable.row_blue);
}
}
// </EDIT SOLUTION>
// call the own implementation
bindHolder(holder);
return view;
}
我真的很感激任何想法如何解决这个问题!
标签:android,java,listview,onclick,background-image 来源: https://codeday.me/bug/20190916/1807777.html