【问题标题】:How can I change the color of selected item from ListView?如何从 ListView 更改所选项目的颜色?
【发布时间】:2015-01-07 20:45:20
【问题描述】:

我创建了一个 android 项目,其中有一个包含 6 个项目的列表视图。 我希望每次从列表中选择任何项目时,它都会保持橙色,直到我按下按钮提交。

代码是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.SafeWalkApp.SecondActivity" >

     <ListView
        android:id="@+id/sampleListView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="5dp"
        android:background="@android:color/transparent"
        android:cacheColorHint="@android:color/transparent"
        android:divider="#CCCCCC"
        android:dividerHeight="1dp"
       android:entries="@array/vol_list" >
    </ListView>

     <Button
         android:id="@+id/onsubmit"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_centerHorizontal="true"
         android:text="@string/submit" />

</RelativeLayout>

这是我的 xml 代码。 我尝试将颜色添加到 color.xml ,但这向我显示了一条错误消息,基本上它是针对背景的。所以请帮我解决这个问题。

【问题讨论】:

标签: java android listview


【解决方案1】:

如果您使用的是自定义列表视图并且有一个由自定义适配器设置的项目,那么您可以在

中更改列表视图项目的颜色

nList = (ListView) findViewById(android.R.id.yourlistname); nList.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {

    }
});

在上面的函数 nList 是您要在其中进行更改的列表,在其单击列表器中,您可以获取所选项目视图,其参数为 View arg1,从中您可以获取线性布局及其所有其他控件并根据需要更改任何控件颜色、文本等

在此处获取视图并通过获取视图并设置其背景等来设置所需的任何颜色。 我不能在这里写完整的代码,但我希望你能得到我的?

【讨论】:

  • 我无法得到那个我将在哪里添加你建议的行..?以及“在这里获得视图”是什么意思..thnx
【解决方案2】:

您必须创建状态可绘制颜色。还有一些 xml.files 可以根据行的状态定义不同的颜色。

也许这对你有帮助。

How to change color of ListView items on focus and on click

Android LinearLayout with color resource: What am I doing wrong?

【讨论】:

    【解决方案3】:
    1. 创建一个类,其中包含适配器项所需的所有信息 + 一个布尔变量,您将在适配器 getView 中检查,如果该变量为真,则将颜色更改为橙​​色,否则为正常颜色.
    2. 在 onItemClick 中找到您提供给适配器的列表中正确对象的位置并更改其布尔值。
    3. 之后刷新适配器引用列表。
    4. 在您的适配器上调用 notifyDataSetChanged()。现在根据第 (1.) 点,适配器将检查项目的布尔值并将其颜色更改为橙​​色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 2014-10-25
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多