Android SettingsActivity,如何触发BackButton

Android SettingsActivity, how to trigger BackButton

我正在开发的应用程序将 运行 放在平板电脑上,平板电脑将被放置在 "cage" 内,以防止用户删除它。 "cage" 将重新创建 Kiosk 模式; android 带有后退按钮和主页按钮的按钮栏将无法被用户实际访问。

在主要活动和片段中,我设法通过在某些按钮的 OnClickListener 中调用 onBackPressed() "go back"。

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

如果我只能在布局中显示首选项,我不知道如何操作 onBackPressed()。

我尝试添加一个名为 GoBack 的开关首选项并创建一个连续刷新的处理程序并检查 GoBack 首选项是否为 True,在这种情况下我会将其设置为 false 并触发 onBackPressed();但它没有用,返回没有改变,应用程序崩溃了,我无法让它工作。

这是 SettingActivity 代码(android 工作室之一)

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);
    }
}

}

这是首选项屏幕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>

您可以保留一个按钮并在单击该按钮时调用:

finishActivity(); 

这将在您的 activity 堆栈中强制 return 到上一个 activity。

1.Back Activity

中的按钮

复制布局

com.android.internal.R.layout.preference_list_content_single

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

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

}

2.Back 片段布局中的按钮

复制布局

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() 将销毁 activity,如果您需要,这可能没有用导航回较早的片段)

编辑:我还没有测试过,但它应该可以工作

这样解决的问题:

我制作了另一个自定义主题,仅用于显示带有后退按钮的操作栏的设置。

它工作正常,感谢大家:)