Preference
我可以随意设置所有项目的背景样式。如何将一些Pereference
项目设置为一种风格(例如设置 a listSelector
)并为其余Preference
项目设置不同的风格?
我将样式设置为Preference
设置其布局的样式:
<style name="Preference.Custom">
<item name="android:layout">@layout/preference_custom</item>
<item name="android:background">@color/transparent</item>
</style>
在中preference_custom.xml
,我再次设置了背景:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="@dimen/spacing_large"
android:gravity="center_vertical"
android:background="@color/transparent"> <--- Here's where I set the background
...
除按下状态的背景外,所有自定义样式都已设置。
我还尝试将背景设置为可绘制的,将按下状态设置为透明。
在我的 Preference 自定义类中,我设置了背景,我看到它从顶部条目变为底部条目,如下所示:
android.graphics.drawable.ColorDrawable@41e30248
android.graphics.drawable.ColorDrawable@41de71d8
这是我的子类Preference
:
public class PreferenceNoBackground extends Preference {
private Context mContext;
public PreferenceNoBackground(Context context) {
super(context);
mContext = context;
}
public PreferenceNoBackground(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
public PreferenceNoBackground(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
view.setBackgroundResource(R.drawable.item_background_transparent);
}
}
item_background_transparent.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:drawable="@color/transparent" />
<!-- Even though these two point to the same resource, have two states so the drawable will invalidate itself when coming out of pressed state. -->
<item android:state_focused="true" android:state_enabled="false" android:state_pressed="true" android:drawable="@color/transparent" />
<item android:state_focused="true" android:state_enabled="false" android:drawable="@color/transparent" />
<item android:state_focused="true" android:state_pressed="true" android:drawable="@color/transparent" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@color/transparent" />
<item android:state_focused="true" android:drawable="@color/transparent" />
<item android:drawable="@color/transparent" />
</selector>
我还尝试从以下设置背景PreferenceFragment
:
pref = findPreference(Settings.CUSTOM);
pref.setOnPreferenceClickListener(this);
pref.getView(null, null).setBackground(getResources().getDrawable(
R.drawable.item_background_transparent));