我在首选项屏幕上添加了一个小部件布局,显示一个箭头图标,以向用户表明在给定的PreferenceScreen后面有更多的首选项。
但是,我注意到当PreferenceScreen未启用时,它会变暗。有没有办法改变正在使用的小部件布局,或者让它成为有状态的,这样当我的PreferenceScreen被禁用时,我就可以使用一个淡入淡出的图标?类似于可以将状态列表可绘制应用为按钮的背景?
tl;dr:当PreferenceLayout实例被禁用时,如何更改显示的图标?
发布于 2011-06-02 20:55:27
这可以通过3个步骤单独使用XML来完成。
首先,创建一个有状态的可绘制文件,该文件可以根据使用它的小部件是否被启用、禁用等进行更改。因此,statelist_example.xml保存在可绘制文件夹中:
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/expander_ic_minimized"
android:state_enabled="true" />
<item
android:drawable="@drawable/expander_ic_minimized_faded"
android:state_enabled="false" />
</selector>然后定义您自己的布局,以使用该可绘制的布局文件夹中的布局。这将成为首选项的"widgetLayout“。所以layout_example.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+android:id/widget_frame"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/icon"
android:src="@drawable/statelist_example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dip"
android:layout_marginRight="6dip"
android:layout_gravity="center" />
</LinearLayout>第三,在每个首选项中指定要使用此布局的widgetLayout:
<Preference
android:key="preference_example"
android:title="@string/preference_title"
android:widgetLayout="@layout/layout_example" />所以基本上你的偏好引用了一个布局,这个布局引用了一个有状态的可绘制对象。
Android Docs on Statelist Drawable.
Android Docs on Preference widgetLayout.
发布于 2011-06-02 04:29:55
很好的方法
我所能看到的解决这个问题的最好的方法是创建你自己的类,它扩展了一个Preference/PreferenceScreen。您需要的布局资源在类的初始化过程中被调用:
setWidgetLayoutResource(R.layout.preference_color); 它创建要在窗口小部件区域中显示的视图,我认为当禁用首选项时,该视图不会变灰。
黑客/丑陋方法
恐怕我只想出了一个解决这个问题的办法,我不相信小部件支持状态。
只需通过编程更改小部件即可:
Preference BGColor = findPreference("Setting_BG_Color");
BGColor.setWidgetLayoutResource(R.layout.ic_custom);然后在每次调用依赖项时更改小部件布局(有点混乱)。
pref1 = (Preference) findPreference("Setting_Pref1");
pref1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Check what object returned (assume checkbox pref)
if ((boolean)newValue){
BGColor.setWidgetLayoutResource(R.layout.ic_custom2);
}
return true;
}
}); https://stackoverflow.com/questions/5857541
复制相似问题