我有一个 ListFragment,它在每个列表项中都包含一个 Button。单击 Button 时,Button 的颜色会发生变化(使用 Drawable xml 资源)。虽然 Button 的颜色在点击事件期间发生变化,但它的颜色在事件发生后变回默认值,即颜色变化在点击期间暂时可见,而不是之后。我真正想要发生的是在事件触发后颜色变化持续存在。
我尝试了一种通过 ListFragment 的自定义适配器(在我的例子中是 SimpleAdapter)的 getView(int position, View convertView, ViewGroup parent) 方法来操作项目 View 的方法,我可以在其中存储项目的位置并保留背景每个按钮的状态。但是我想使用选择器复制这个解决方案。
我有两个 Drawable 资源为每个 Button 的按下和单击状态设置颜色,还有管理这些状态的选择器资源。
这是我操纵颜色状态的可绘制资源:
<?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>
我无法解决这个问题,任何方向、指导或解决方案将不胜感激。
最佳答案
将以下代码添加到您的Adapter
类的getView()
方法中:
@Override
public void getView(int position, View view, ViewGroup parent){
final Button b = (Button) view.findViewById(R.id.button);
b.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
b.setBackgroundResource(R.drawable.clicked_drawable);
.....
.....
}
....
....
}
试试这个。它会起作用。
关于android - 使按钮的背景颜色发生变化并在单击后保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24094885/