Adding custom layout to PreferenceFragment

后端 未结 2 703
有刺的猬
有刺的猬 2021-01-05 05:47

I have a preference fragment with a preference screen hierarchy. I would like to add a custom layout to define an \"about the author\" section, adding imageview to an elemen

2条回答
  •  佛祖请我去吃肉
    2021-01-05 05:51

    This is just a follow up to the answer by Carmen (30 October 2016):

    If you want to dynamically change the properties on your custom layout, after the screen has loaded, you cannot use something like this:

    PreferenceScreen customPref = (PreferenceScreen) findPreference("customPreference");
    View prefRow = customPref.getView(null, null);
    ImageView imageView = (ImageView)prefRow.findViewById(R.id.image_view);
    imageView.setImageResource(R.drawable.whatever);
    

    Although it won't crash, it will not actually do anything. It's odd and confusing.

    You have to use a custom class that extends android.preference.Preference and override onBindView() to change properties on the custom layout. The technique is explained here: How to manage custom preference layout [Note: For PreferenceFragmentCompat, you have to extend androidx.preference.Preference and override onBindViewHolder()]

    Another way is to use getView() but ensure that you use View view = super.getView(convertView, parent);: Android Set Custom Preference Layout

提交回复
热议问题