【发布时间】:2014-06-07 07:27:22
【问题描述】:
我有一个 ListFragment,它在每个列表项中都包含一个 Button。单击 Button 时,Button 的颜色会发生变化(使用 Drawable xml 资源)。尽管 Button 的颜色在单击事件期间发生了变化,但它的颜色在事件发生后会变回其默认值,即颜色变化在单击期间是暂时可见的,而不是在之后。我真正希望发生的是在事件触发后颜色变化持续存在。
我尝试了一种通过 ListFragment 的自定义适配器(在我的情况下为 SimpleAdapter)的 getView(int position, View convertView, ViewGroup parent) 方法来操作项目视图的方法,我可以在其中存储项目的位置并保持背景每个按钮的状态。但是我想使用选择器来复制这个解决方案。
我有两个可绘制资源为每个按钮的按下和单击状态以及管理这些状态的选择器资源设置颜色。
这是我操纵颜色状态的可绘制资源:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true"
android:drawable="@drawable/clicked_drawable" /> <!-- pressed -->
<item android:state_focused="false" android:state_pressed="false"
android:drawable="@drawable/clicked_drawable" />
<item android:drawable="@drawable/unclicked_drawable" /> <!-- default -->
</selector>
以及包含不同颜色的两个资源,clicked_drawable.xml & unclicked_drawable.xml,依次为:
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="#F08080"
/>
</shape>
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="#FFB00F"
/>
</shape>
ListFragment 的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1"
android:descendantFocusability="blocksDescendants"
android:layout_margin="5dp"
>
<ListView android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/label"
android:gravity="start"
/>
<TextView
android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
/>
</LinearLayout>
<Button
android:id="@+id/button_1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/button"
android:layout_margin="2dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:clickable="true"
android:background="@drawable/selector_drawable"
/>
</LinearLayout>
我无法解决此问题,我们将不胜感激任何方向、指导或解决方案。
【问题讨论】:
-
您需要以编程方式进行\
-
您应该以编程方式进行,例如为您的按钮添加标签,并在不同的标签上将按钮的背景设置为不同的东西
-
如果它是一个列表片段,那么您需要在适配器的 getview 方法中应用颜色更改
标签: android android-fragments android-listview android-view android-adapter