Android SettingsActivity,如何触发BackButton

时间:2017-02-08 10:28:18

标签: android sharedpreferences android-settings

我正在开发的应用程序将在平板电脑上运行,该平板电脑将放置在“笼子”内以防止用户将其移除。 这个“笼子”将重建一个Kiosk模式;用户无法实际访问带有背面和主页按钮的Android按钮栏。

在主要活动和片段中,我通过在某些按钮的OnClickListener中调用onBackPressed()来设法“返回”。

现在问题是我必须添加设置活动,这种活动不使用普通布局而是使用PreferenceScreen。

如果在布局中可以显示的唯一内容是优先选择,我无法弄清楚如何操作onBackPressed()。

我尝试添加一个名为GoBack的switchpreference并创建一个刷新的处理程序,并检查GoBack首选项是否为True,在这种情况下我会将其设置为false并触发onBackPressed();但它不起作用,Go Back没有改变,应用程序崩溃,我无法使其正常工作。

这是SettingActivity代码(android studio one)

public class SettingsActivity extends AppCompatPreferenceActivity {


private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
    @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
        String stringValue = value.toString();


        if (preference instanceof ListPreference) {
            // For list preferences, look up the correct display value in
            // the preference's 'entries' list.
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(stringValue);

            // Set the summary to reflect the new value.
            preference.setSummary(
                    index >= 0
                            ? listPreference.getEntries()[index]
                            : null);

        } else if (preference instanceof RingtonePreference) {
            // For ringtone preferences, look up the correct display value
            // using RingtoneManager.
            if (TextUtils.isEmpty(stringValue)) {
                // Empty values correspond to 'silent' (no ringtone).
                preference.setSummary(R.string.pref_ringtone_silent);

            } else {
                Ringtone ringtone = RingtoneManager.getRingtone(
                        preference.getContext(), Uri.parse(stringValue));

                if (ringtone == null) {
                    // Clear the summary if there was a lookup error.
                    preference.setSummary(null);
                } else {
                    // Set the summary to reflect the new ringtone display
                    // name.
                    String name = ringtone.getTitle(preference.getContext());
                    preference.setSummary(name);
                }
            }

        } else {
            // For all other preferences, set the summary to the value's
            // simple string representation.
            preference.setSummary(stringValue);
        }
        return true;
    }
};

/**
 * Helper method to determine if the device has an extra-large screen. For
 * example, 10" tablets are extra-large.
 */
private static boolean isXLargeTablet(Context context) {
    return (context.getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}

/**
 * Binds a preference's summary to its value. More specifically, when the
 * preference's value is changed, its summary (line of text below the
 * preference title) is updated to reflect the value. The summary is also
 * immediately updated upon calling this method. The exact display format is
 * dependent on the type of preference.
 *
 * @see #sBindPreferenceSummaryToValueListener
 */
private static void bindPreferenceSummaryToValue(Preference preference) {
    // Set the listener to watch for value changes.
    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

    // Trigger the listener immediately with the preference's
    // current value.
    try {
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }
    catch (Exception e)
    {
        try {
            sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                    PreferenceManager
                            .getDefaultSharedPreferences(preference.getContext())
                            .getBoolean(preference.getKey(),false));
        }
        catch (Exception ex)
        {
            Log.e("Impostazioni","Impossibile eseguire Sett.Binding di "+preference.getKey());
        }
    }
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setupActionBar();
}

/**
 * Set up the {@link android.app.ActionBar}, if the API is available.
 */
private void setupActionBar() {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        // Show the Up button in the action bar.
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        if (!super.onMenuItemSelected(featureId, item)) {
            NavUtils.navigateUpFromSameTask(this);
        }
        return true;
    }
    return super.onMenuItemSelected(featureId, item);
}

/**
 * {@inheritDoc}
 */
@Override
public boolean onIsMultiPane() {
    return isXLargeTablet(this);
}

/**
 * {@inheritDoc}
 */
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
    loadHeadersFromResource(R.xml.pref_headers, target);
}

/**
 * This method stops fragment injection in malicious applications.
 * Make sure to deny any unknown fragments here.
 */
protected boolean isValidFragment(String fragmentName) {
    return PreferenceFragment.class.getName().equals(fragmentName)
            || GeneralPreferenceFragment.class.getName().equals(fragmentName)
            || DataSyncPreferenceFragment.class.getName().equals(fragmentName)
            || NotificationPreferenceFragment.class.getName().equals(fragmentName);
}

/**
 * This fragment shows general preferences only. It is used when the
 * activity is showing a two-pane settings UI.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_general);
        setHasOptionsMenu(true);

        // Bind the summaries of EditText/List/Dialog/Ringtone preferences
        // to their values. When their values change, their summaries are
        // updated to reflect the new value, per the Android Design
        // guidelines.
        bindPreferenceSummaryToValue(findPreference("PassWordImpostazioni"));
        //bindPreferenceSummaryToValue(findPreference("example_list"));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            startActivity(new Intent(getActivity(), SettingsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

/**
 * This fragment shows notification preferences only. It is used when the
 * activity is showing a two-pane settings UI.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_notification);
        setHasOptionsMenu(true);

        // Bind the summaries of EditText/List/Dialog/Ringtone preferences
        // to their values. When their values change, their summaries are
        // updated to reflect the new value, per the Android Design
        // guidelines.
        /*bindPreferenceSummaryToValue(findPreference("LedBattutaPorta"));
        bindPreferenceSummaryToValue(findPreference("SpoilerPosteriore"));
        bindPreferenceSummaryToValue(findPreference("LuciBianche"));
        bindPreferenceSummaryToValue(findPreference("Scalino"));
        bindPreferenceSummaryToValue(findPreference("Webasto"));
        bindPreferenceSummaryToValue(findPreference("Stufa220V"));*/


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            startActivity(new Intent(getActivity(), SettingsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

/**
 * This fragment shows data and sync preferences only. It is used when the
 * activity is showing a two-pane settings UI.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_data_sync);
        setHasOptionsMenu(true);

        // Bind the summaries of EditText/List/Dialog/Ringtone preferences
        // to their values. When their values change, their summaries are
        // updated to reflect the new value, per the Android Design
        // guidelines.
        bindPreferenceSummaryToValue(findPreference("sync_frequency"));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            startActivity(new Intent(getActivity(), SettingsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

}

这是PreferenceScreen XML

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory
    android:title="OPT. Luci"
    android:key="OptLuci">
    <SwitchPreference
        android:defaultValue="false"
        android:key="LedBattutaPorta"
        android:title="Pulsante Disabilitazione Led Battuta Porta" />
    <SwitchPreference
        android:defaultValue="false"
        android:key="SpoilerPosteriore"
        android:title="Pulsante Disabilitazione Spoiler Posteriore" />
    <SwitchPreference
        android:defaultValue="false"
        android:key="LuciBianche"
        android:title="Pulsante Disabilitazione Luci Bianche" />
</PreferenceCategory>
<PreferenceCategory
    android:title="OPT. Servizi"
    android:key="OptServizi">
    <SwitchPreference
        android:defaultValue="false"
        android:key="Scalino"
        android:title="Pulsante Disabilitazione Scalino" />

</PreferenceCategory>
<PreferenceCategory
    android:title="OPT. Clima"
    android:key="OptClima">
    <SwitchPreference
        android:defaultValue="false"
        android:key="Webasto"
        android:title="Webasto" />
    <SwitchPreference
        android:defaultValue="false"
        android:key="Stufa220V"
        android:title="Stufa 220V" />
</PreferenceCategory>

<PreferenceCategory
    android:title="OPT. Vano Sanitario"
    android:key="OptVanoSanitario">

    <SwitchPreference
    android:defaultValue="false"
    android:key="Bombola1"
    android:title="Presenza Bombola 1" />
    <SwitchPreference
        android:defaultValue="false"
        android:key="Bombola2"
        android:title="Presenza Bombola 2" />

</PreferenceCategory>

3 个答案:

答案 0 :(得分:0)

您可以按住按钮,然后点击按钮,拨打:

finishActivity(); 

这将强制返回活动堆栈中的上一个活动。

答案 1 :(得分:0)

1.活动中的按钮

复制布局

<强> com.android.internal.R.layout.preference_list_content_single

添加后退按钮并覆盖onCreate以设置新布局

  @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(yourLayout)

}

2.片段布局中的背景按钮

复制布局

<强> com.android.internal.R.layout.preference_list_fragment

并添加后退按钮

    @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {

    TypedArray a = getActivity().obtainStyledAttributes(null,
                                                        com.android.internal.R.styleable.PreferenceFragment,
                                                        com.android.internal.R.attr.preferenceFragmentStyle,
                                                        0);

    int yourLayout = R.layout.your_layout; //put your custom layout here
    yourLayout = a.getResourceId(com.android.internal.R.styleable.PreferenceFragment_layout,
                                   yourLayout);

    a.recycle();

    return inflater.inflate(yourLayout, container, false);
}

将OnClickListener注册到该按钮并调用Activity的onBackPressed(),这将触发后退操作(finish()将销毁该活动,如果您想要导航回更早的片段,这可能没用)

编辑:我没有测试过,但它应该可以运行

答案 2 :(得分:0)

问题以这种方式解决了:

我为我使用后退按钮显示操作栏的设置制作了另一个自定义主题。

它很好,感谢大家:)