How to add a button to a PreferenceScreen?

后端 未结 10 1209
抹茶落季
抹茶落季 2020-11-28 20:48

I\'m quite new to Android Development and just came across Preferences. I found PreferenceScreen and wanted to create a login functionality with it. The only pr

相关标签:
10条回答
  • 2020-11-28 21:14

    I don't think there is an easy way to just add a Button to a preference screen. Preferences are limited to:

    EditTextPreference
    ListPreference
    RingtonePreference
    CheckboxPreference
    

    While using a preference screen, you are limited to the use of these options, and there are no single "button-preference" which could be easily used for your need.

    I've been looking for similar functionality, with adding buttons to the preference screen, but it seems like you need to build your own screen for this, managing the change to preferences in your own implementation.

    0 讨论(0)
  • 2020-11-28 21:14

    If you'd like to catch a user click on one of the Preferences items and your app is using PreferenceFragmentCompat, then you can do this:

    <PreferenceScreen
    ...
    >
    ...
    <Preference
        android:key="@string/pref_key_clickable_item"
        android:persistent="false"
        android:title="Can be clicked"
        android:summary="Click this item so stuff will happen"/>
    ...
    </PreferenceScreen>
    

    Java:

    @Override
    onPreferenceTreeClick(Preference preference) {
        if (preference.getKey().equals(getContext().getString(R.string.pref_key_clickable_item))) {
           // user clicked the item
           // return "true" to indicate you handled the click
           return true;
        }
        return false;
    }
    

    Kotlin:

    override fun onPreferenceTreeClick(preference: Preference): Boolean {
        if (preference.key == context?.getString(R.string.pref_key_clickable_ite)) {
           // user clicked the item
           // return "true" to indicate you handled the click
           return true
        }
        return false
    }
    
    0 讨论(0)
  • 2020-11-28 21:17

    I suppouse its too late. This is what i have done for a Button Preference.

    The preference in preference.xml file in xml folder

    ....
        <Preference
            android:key="resetBD"
            android:title="@string/ajustes_almacenamiento"
            android:summary="@string/ajustes_almacenamiento_desc"
            android:widgetLayout="@layout/pref_reset_bd_button" 
        ></Preference>
      ...
    

    and pref_reset_bd_button.xml in layout folder

     <?xml version="1.0" encoding="utf-8"?>
       <Button
           xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/resetButton" 
            android:text="@string/ajustes_almacenamiento_bt" 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="resetearBD">
    
       </Button>
    
    0 讨论(0)
  • 2020-11-28 21:19

    Create a custom layout for the SettingsFragment.java i.e layout_settings.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.settings.SettingsFragment"
        tools:ignore="NewApi">
    
        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appBarSettings"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppBarOverlay">
    
            <com.google.android.material.appbar.MaterialToolbar
                android:id="@+id/toolbarSettings"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:minHeight="?attr/actionBarSize"
                app:title="@string/fragment_title_settings" />
        </com.google.android.material.appbar.AppBarLayout>
    
        <!--this works as the container for the SettingsFragment.java
        put the code for the Button above or below this FrameLayout
        according to your requirement-->
    
        <FrameLayout
            android:id="@android:id/list_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
          app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior" />
    
    
        <com.google.android.material.button.MaterialButton
            android:id="@+id/btnSample"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center"
            android:text="@string/button_sample_text" />
    
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    

    Then, refer to the layout file in your styles.xml:

    <style name="AppTheme" parent="....">
          ...............
          ...............
          <item name="preferenceTheme">@style/MyPreferenceThemeOverlay</item>
    </style>
    
    <style name="MyPreferenceThemeOverlay" parent="PreferenceThemeOverlay">
          <item name="android:layout>@layout/layout_settings</item>
    </style>
    

    And then, in the onViewCreated() method of your SettingsFragment.java, you can use the button like this:

        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle 
                                 savedInstanceState) {
    
            MaterialButton btnSample = view.findViewById(R.id.btnSample);
            btnSample.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(requireContext(), "Sample Button 
                       clicked!!", Toast.LENGTH_LONG).show();
                }
            });
        }
    

    0 讨论(0)
  • 2020-11-28 21:22

    You can also customise the layout of a Preference by overriding Preference.onCreateView(parent). The example below uses an anonymous inner class to make red preferences.

        screen.addPreference(
            new Preference(context) {
                @Override
                protected View onCreateView(ViewGroup parent) {
                    View view = super.onCreateView(parent);
                    view.setBackgroundColor(Color.RED);
                    return view;
                }
            });
    

    You could use this technique to add a button to the default view.

    0 讨论(0)
  • 2020-11-28 21:27

    I wanted to add an Exit link to the preferences and was able to modify Jakar's code to make it work like this:

    <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >   
       <PreferenceCategory android:title="Settings">
           <Preference android:title="Click to exit" android:key="exitlink"/>       
       </PreferenceCategory>    
    </PreferenceScreen>
    

    Originally the 'Preference' was a 'EditTextPreference' which I hand edited.

    Then in the class:

    public class MyPreferences extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.mypreferences);
    
        Preference button = (Preference)getPreferenceManager().findPreference("exitlink");      
        if (button != null) {
            button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference arg0) {
                    finish();   
                    return true;
                }
            });     
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题