Android自定义preference

1.自定义preference
public class MyPreference extends Preference {


public MyPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
setWidgetLayoutResource(R.layout.arrow_next);
}

public MyPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setWidgetLayoutResource(R.layout.arrow_next);
}

public MyPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setWidgetLayoutResource(R.layout.arrow_next);
}

public MyPreference(Context context) {
super(context);
setWidgetLayoutResource(R.layout.arrow_next);
}

@Override
public void onBindViewHolder(PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
initPreferenceStyle(holder);
}
   public void initPreferenceStyle(PreferenceViewHolder holder) {
holder.itemView.setPadding(25, 8, 25, 8);
TextView txtTitle = (TextView) holder.findViewById(android.R.id.title);
txtTitle.setTextSize(20);
}
}
2.加入preference.xml
<PreferenceScreen>
    <com.example.preference.MyListPreference
app:allowDividerAbove="true"
app:defaultValue="@string/value_language_cn"
app:entries="@array/entries_language"
app:entryValues="@array/entry_values_language"
app:icon="@drawable/ic_setting_language"
app:key="language"
app:summary="@string/language_cn"
app:title="@string/settings_language" />

</PreferenceScreen>
3.加载prefrence
public class SettingsActivity extends BaseActivity {

@Override
public void onCreate() {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings_container, new SettingsFragment())
.commit();
}
}
public class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle bundle, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
}
posted @ 2020-10-13 14:45  Jokeyyu  阅读(707)  评论(0编辑  收藏  举报