本文介绍了将按钮添加到PreferenceFragment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在首选项屏幕的底部添加几个按钮,用于设置默认值和恢复默认值.答案未涵盖如何使用PreferenceFragment进行此操作.推荐的实现方法是什么.

I want to add a couple buttons to the bottom of my preferences screen for setting defaults and restoring defaults. This answer doesn't cover how to do this using PreferenceFragment. What is the recommended way to accomplish this.

加载首选项片段的活动:

Activity that loads the preferences fragment:

public class SettingsActivity extends Activity {

    @Override
    public void onCreate( Bundle savedInstanceState) {

        super.onCreate( savedInstanceState);

        // load up the preferences fragment
        getFragmentManager().beginTransaction().replace( android.R.id.content, new PrefsSettingsFragment()).commit();
    }
}

PreferenceFragment实现:

PreferenceFragment implementation:

public class PrefsSettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate( Bundle savedInstanceState) {

        super.onCreate( savedInstanceState);

        addPreferencesFromResource( R.xml.preferences);
    }
}

preferences.xml:

preferences.xml:

<?xml version="1.0"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <EditTextPreference android:key="edit_text_preference_server_address" android:title="@string/preference_server_address"/>
    <SwitchPreference android:key="switch_preference_bat" android:title="@string/preference_bat"/>
    <SwitchPreference android:key="switch_preference_comm" android:title="@string/preference_comm"/>
    <SwitchPreference android:key="switch_preference_dev_mode" android:title="@string/preference_dev_mode" android:defaultValue="true"/>

</PreferenceScreen>

推荐答案

我遇到了同样的问题,并且找到了解决此问题的方法.

I meet the same question, and I found a way to handle this issue.

使用给定的LayoutInfalter by参数覆盖PreferenceFragment中的onCreateView方法,以创建您自己的视图,然后返回该视图.

Overwrite the method onCreateView in PreferenceFragment, using the given the LayoutInfalter by parameters to create your own View, and return this view.

这是我的代码.我希望这会有所帮助

It's my code. I hope this can be helpful

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        View v = inflater.inflate(R.layout.set_alarm, null);

        Button save = (Button)v.findViewById(R.id.save);
        Button revert = (Button)v.findViewById(R.id.revert);
        Button delete = (Button)v.findViewById(R.id.delete);

        save.setOnClickListener(this);
        revert.setOnClickListener(this);
        delete.setOnClickListener(this);

        if(mId == -1){
            delete.setEnabled(false);
        }

        return v;
    }

这篇关于将按钮添加到PreferenceFragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 22:37