Java Android设置自定义首选项布局
我正在从事it Android项目。我有一个prefs.xml代码,类似这样Java Android设置自定义首选项布局,java,android,Java,Android,我正在从事it Android项目。我有一个prefs.xml代码,类似这样 <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <Preference android:key="pref_name_color_picker"
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:key="pref_name_color_picker"
android:title="Colour"
android:summary="Colour of the name"
android:defaultValue="#FFFFFF"
android:layout="@layout/custom_name_setting_layout" />
</PreferenceCategory>
</PreferenceScreen>
我的问题是;我写的是setBackgroundColor方法,但不起作用。不工作意味着,这个程序运行时没有错误(就像NullReferenceException一样,没有错误)。但背景色仍然没有改变
我不知道为什么。我怎样才能解决这个问题?
谢谢显然,如果您正在硬编码颜色,那么您可以在XML中执行:
android:background="@android:color/red"
如果您想在代码中完成它,那么不幸的是,它比看起来更复杂。您不能只在onCreate()
中设置首选项视图的颜色,因为首选项视图存储在列表中,并在滚动列表时动态创建和循环
创建视图时,需要设置背景色。为此,您需要实现一个自定义的首选项类并重写getView()
:
将XML更改为使用CustomColorPreference
类:
<com.example.yourapp.CustomColorPreference
android:key="pref_name_color_picker"
android:title="Colour"
android:summary="Colour of the name"
android:defaultValue="#FFFFFF"
android:layout="@layout/custom_name_setting_layout" />
是的,但是颜色id将动态变化。这个示例,对于这个示例,我写Color.red。您需要使用ListView。您可以使用
findViewById(android.R.id.list)
回忆它,请给我一个使用的示例。因为我对Android编程还不熟悉,谢谢。
android:background="@android:color/red"
public class CustomColorPreference extends Preference
{
int backgroundColor = Color.BLACK;
public CustomColorPreference(Context context) {
super(context);
}
public CustomColorPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setCustomBackgroundColor(int color)
{
backgroundColor = color;
}
@Override
public View getView(View convertView, ViewGroup parent)
{
View v = super.getView(convertView, parent);
// v.setBackgroundColor(backgroundColor); // set background color of whole view
ImageView ivNameTextColor = (ImageView)v.findViewById(R.id.ivNameTextColor);
ivNameTextColor.setBackgroundColor(backgroundColor);
return v;
}
}
<com.example.yourapp.CustomColorPreference
android:key="pref_name_color_picker"
android:title="Colour"
android:summary="Colour of the name"
android:defaultValue="#FFFFFF"
android:layout="@layout/custom_name_setting_layout" />
CustomColorPreference picker = (CustomColorPreference)findPreference("pref_name_color_picker");
picker.setCustomBackgroundColor(Color.RED);