Android设置页面PreferenceFragment使用详细
文章目录Android设置页面PreferenceFragment使用详细一 设置页面核心代码二 设置页面布局核心代码三SettingFragment核心代码四 setting.xml核心代码五 本文例子一份六 尾言
本文Demo
一 设置页面核心代码
/*
* 创建者: KX
* 创建时间: 2018/12/10 22:17
* 描述: 设置页面
*/
public class SettingActivity extends BaseActivity {
@BindView(R.id.toolbar)
Toolbar mToolbar;
@Override
protected int getlayoutId() {
return R.layout.activity_setting;
}
@Override
protected void init() {
}
@Override
protected void initListener() {
}
@Override
protected void initData() {
mToolbar.setTitle("设置");
//获取内置SP
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
//获取指定key
boolean push = sp.getBoolean("push", false);
Toast("push = "+push );
}
}
12345678910111213141516171819202122232425262728293031323334353637
二 设置页面布局核心代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/toolbar"/>
<!--fragmnet标签一定要一个id-->
<fragment
android:id="@+id/setting_fragment"
android:layout_width="match_parent"
class="com.kx.myplayer.ui.fragment.SettingFragment"
android:layout_height="match_parent"/>
</LinearLayout>
1234567891011121314
三SettingFragment核心代码
/*
* 创建者: KX
* 创建时间: 2018/12/11 20:33
* 描述: SettingFragment
*/
public class SettingFragment extends PreferenceFragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
addPreferencesFromResource(R.xml.setting);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
String key = preference.getKey();
switch (key) {
case "clear_cache":
showToast("clear_cache");
break;
case "push":
showToast("push");
break;
case "no_wifi":
showToast("no_wifi");
break;
case "about":
showToast("about");
break;
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public void showToast(String msg) {
Toast toast = null;
if (toast == null) {
toast = Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_SHORT);
} else {
toast.setText(msg);
}
toast.show();
}
}
123456789101112131415161718192021222324252627282930313233343536373839404142
四 setting.xml核心代码
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:key="clear_cache"
android:title="清楚缓存"/>
<SwitchPreference
android:key="push"
android:title="推送通知"/>
<SwitchPreference
android:key="wifi_update"
android:title="wifi下自动更新"/>
<Preference
android:key="about"
android:title="版本1.0"/>
</PreferenceScreen>
123456789101112131415161718192021