java - Android ListView ,更改特定 View 的属性

标签 java android listview view

在我的 ListView 上,我滚动到它的特定位置,如下所示

getListView().smoothScrollToPosition(scrollposition+1);

但我也想“强调”这个观点。如何访问此特定 View 的属性以更改此位置的背景颜色。

这是 ListView 代码

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/currentText"
    android:padding="10dp" android:textSize="24sp" android:textColor="#000000" android:background="@drawable/bglistitem"
    android:gravity="center_vertical|center_horizontal">
</TextView>

它只是一个带有背景的 TextView 。我尝试这样做:

View highlightView = getListView().getChildAt(scrollposition);
highlightView.setDrawingCacheBackgroundColor(Color.parseColor("#2580b0"));
TextView currentText = (TextView)highlightView.findViewById(R.id.currentText);
currentText.setTextColor(Color.parseColor("#ffffff"));

但它总是崩溃!我可以理解为什么 setDrawingCacheBackgroundColor 崩溃,但即使从该 View 获取 TextView 也会崩溃。

帮忙?

最佳答案

几周前我遇到了这个问题。

您不应使用 ListView 的 getChildAt() 函数。例如,如果您使用 getChildAt(5),它将拉出第 5 个可见的 View 。

为了解决这个问题,我必须创建一个自定义适配器来覆盖 getView() 并根据我发送的内容设置颜色。

  public class RunAdapter extends SimpleAdapter {

public RunAdapter(Context context, List<HashMap<String, String>> items,
        int resource, String[] from, int[] to) {
    super(context, items, resource, from, to);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    TextView txtView = (TextView) view.findViewById(R.id.lstTurnout);
        if (txtView.getText().toString().contains("BLU")) {
            txtView.setBackgroundColor(Color.rgb(0x00, 0x00, 0xaa));
            txtView.setText(txtView.getText().toString().replace("BLU", ""));
        } else {
            txtView.setBackgroundColor(Color.rgb(0xaa, 0x00, 0x00));
            txtView.setText(txtView.getText().toString().replace("RED", ""));
        }
  }

这不是最漂亮的方法,但它确实有效! 根据我想要 TextView 的颜色,我传递了“BLU”或“RED” 然后在 getView 中,我检查字符串包含哪些内容并相应地更改颜色。

希望我能提供一些帮助,祝你好运!

编辑 根据请求构造函数

关于java - Android ListView ,更改特定 View 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7086133/

相关文章:

Java:设置预定长度的数组作为方法参数?

android - 由于 ScrollView,ListView 表现得很奇怪?

java - 相同的图像,但不同的 base64

java - java.lang.NoClassDefFoundError 和 ClassNotFoundException 引起的错误

android - 如何编写自己的复制和粘贴上下文菜单?

android - 将应用程序上下文保存到 Android 中的静态变量是否安全?

安卓 Facebook 图谱 API JSONException 'No value for email'

java - 在ListAdapter(ListView)中重新填充数据的最佳方法

java - 如何在 ListView 中添加分页?

java - 数据数组值不兼容的类型