gpt4 book ai didi

Android ListView 选择的背景在 2.3 中不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:21:49 24 4
gpt4 key购买 nike

我试图让我的应用程序在 2.3 中正常工作(它在 4.0+ 中工作正常),我遇到的一个问题是在我的 ListView 中我无法更改所选项目的背景。我不确定我需要更改什么 - 有人知道吗?

这是 ListView 本身:

<ListView
android:id="@+id/score_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@+id/keyboard"
android:layout_below="@+id/sort_header"
android:choiceMode="singleChoice"
android:divider="#CCCCCC"
android:dividerHeight="1dp"
android:listSelector="@drawable/selector" />

这是适用于 4.0+ 的选择器(在 2.3 中没有颜色变化):

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@color/highlight"/>
<item android:state_pressed="true" android:drawable="@color/highlight"/>
<item android:state_activated="true" android:drawable="@color/highlight"/>
<item android:state_selected="true" android:drawable="@color/highlight"/>
</selector>

实际上这 4 个我都不需要,但我想尝试所有的东西。

最佳答案

我遇到了完全相同的问题。我还没有找到如何在 XML 中执行此操作的方法,但我在代码中找到了解决方法。以下代码在支持 API 级别 7+ 的应用程序中进行了测试

首先,您需要稍微更改一下 ListView 的适配器:

public class ListViewAdapter extends BaseAdapter {
private int selectedItemPosition = -1;

// your code

public void selectItem(int i) {
selectedItemPosition = i;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

// your code

if (i == selectedItemPosition) {
// set the desired background color
textView.setBackgroundColor(context.getResources().getColor(R.color.highlight));
}
else {
// set the default (not selected) background color to a transparent color (or any other)
textView.setBackgroundColor(Color.TRANSPARENT);
}
return view;
}
}

接下来,您必须通知适配器您的 OnItemClickListeneronItemClickMethod 中的选择已更改:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// select the item
((ListViewAdapter) listview.getAdapter()).selectItem(position);
// force redraw of the listview (invalidating just "view" is not enough)
((ListView) parent).invalidateViews();

// your code
}

应该是这样的。现在,只要您不想更改所选项目,就可以使用 onItemClick() 中使用的相同代码,即。 selectItem() 后跟 invalidateViews()。除了调用 invalidateViews(),还可以使用适配器的 notifyDataSetChanged()

此外,您还应该向 ListView 添加适当的 listSelector,以避免在单击项目时默认选择器的短暂闪烁。但是,当整个 View 的背景发生变化时,API 7 和 8 上的列表选择器存在一个错误。您可以找到解决方法 here

关于Android ListView 选择的背景在 2.3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15799021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com