Android设置自定义首选项布局

我正在研究Android项目。 我有一个prefs.xml代码,就像这样

     

我需要自定义首选项布局。 我创造了;

custom_name_setting_layout.xml

         

并编写一个SettingActivity.java

 public class SettingActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { int color = 0xffffff00; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.prefs); LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View row = inflater.inflate(R.layout.custom_name_setting_layout, null); ImageView ivNameTextColor = (ImageView) row.findViewById(R.id.ivNameTextColor); ivNameTextColor.setBackgroundColor(Color.RED); } } 

我的问题是; 我写了setBackgroundColor方法,但没有工作。 不工作意味着,这个程序运行没有错误(如NullReferenceException,没有错误)。 但背景颜色仍然没有改变。

我不知道为什么。 我怎么解决这个问题? 谢谢

显然,如果您对颜色进行硬编码,那么您可以在XML中执行此操作:

 android:background="@android:color/red" 

如果你想在代码中这样做,那么不幸的是它比它看起来更棘手。 您不能只在onCreate()设置首选项视图的颜色,因为首选项视图存储在列表中,并在滚动列表时动态创建和回收。

您需要在创建视图时设置背景颜色。 为此,您需要实现自定义首选项类并覆盖getView()

 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; } } 

更改XML以使用CustomColorPreference类:

  

然后在onCreate您可以使用公共方法setCustomBackgroundColor()获取CustomColorPreference并在其上设置颜色:

 CustomColorPreference picker = (CustomColorPreference)findPreference("pref_name_color_picker"); picker.setCustomBackgroundColor(Color.RED);