【问题标题】:Android SettingsActivity, how to trigger BackButtonAndroid SettingsActivity,如何触发BackButton
【发布时间】:2017-02-08 10:28:17
【问题描述】:

我正在开发的应用程序将在平板电脑上运行,该平板电脑将被放置在“笼子”内以防止用户将其移除。 这个“笼子”将重新创建一个 Kiosk 模式;带有返回和主页按钮的 android 按钮栏将不会被用户物理访问。

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

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

如果我可以在布局中显示的唯一内容是首选项,我不知道如何操作 onBackPressed()。

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

这是 SettingActivity 代码(android studio 之一)

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>

【问题讨论】:

  • 您是否尝试过创建自定义首选项?
  • 您的设计是否允许您使用工具栏?还是操作栏?
  • 我没有经验和时间来创建自定义偏好活动,这就是为什么我要对 android studio one 进行一些修改。
  • 主要活动被固定和全屏,我没有任何操作栏或工具栏。当我进入设置活动时,它不再固定,但实际上我没有任何工具栏或操作栏

标签: android sharedpreferences android-settings


【解决方案1】:

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

finishActivity(); 

这将强制返回到您的活动堆栈中的前一个活动。

【讨论】:

  • 我无法在这种布局中添加按钮,因为它实际上不是布局,而是 ScreenPreference,它只允许您使用一些组件,如 SwichPreference 或 TextPreference。在这种活动中我也无法管理 OnClick 事件
  • 在您的设置活动中使用 PreferenceFragment (developer.android.com/reference/android/preference/…),我认为您也可以在当前状态下使用偏好更改侦听器,但这太脏了..
  • 我正在尝试使用PreferenceFragment,你知道如何用这种frag调用Fragment Replacement吗?我无法像处理普通片段那样处理交易
  • getFragmentManager().beginTransaction() .replace(R.id.preference_container, fragment, SETTINGS_FRAGMENT_TAG) .commit();
  • 如果你想让它正常工作,添加一个 switchPreference 以返回,如果该开关切换为 true,则在你的偏好中更改监听器 finishActivity()
【解决方案2】:

1.Activity中的返回按钮

复制布局

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() 将破坏 Activity,如果您想导航回较早的片段,这可能没有用)

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

【讨论】:

    【解决方案3】:

    问题以这种方式解决:

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

    一切正常,谢谢大家:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      相关资源
      最近更新 更多