How to add a button to PreferenceScreen in Android?

AndroidApps/ApplicationsMobile Development

This example demonstrates how do I add a button to PreferenceScreen in android.

Step 1 − Create a new project in Android Studio, go to File rArr; New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <FrameLayout
      android:id="@+id/settings"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
</LinearLayout>

Step 3 − Add the following code to src/MainActivity.java

import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main_activity);
      getSupportFragmentManager().beginTransaction().replace(R.id.settings, new SettingsFragment()).commit();
      ActionBar actionBar = getSupportActionBar();
      if (actionBar != null) {
         actionBar.setDisplayHomeAsUpEnabled(true);
      }
   }
   public static class SettingsFragment extends PreferenceFragmentCompat {
      @Override
      public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
         setPreferencesFromResource(R.xml.root_preferences, rootKey);
         Preference button = getPreferenceManager().findPreference("toastMsg");
         if (button != null) {
            button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
               @Override
               public boolean onPreferenceClick(Preference arg0) {
                  Toast.makeText(getActivity(), "Preference button is clicked",
                  Toast.LENGTH_SHORT).show();
                  return true;
               }
            });
         }
      }
   }
}

Step 4 − add the following code in the root_preferences.xml

<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
   <PreferenceCategory app:title="@string/messages_header">
      <EditTextPreference
         app:key="signature"
         app:title="@string/signature_title"
         app:useSimpleSummaryProvider="true" />
      <ListPreference
         app:defaultValue="reply"
         app:entries="@array/reply_entries"
         app:entryValues="@array/reply_values"
         app:key="reply"
         app:title="@string/reply_title"
         app:useSimpleSummaryProvider="true" />
      <Preference
         app:key="toastMsg"
         app:title="Show me a Toast" />
   </PreferenceCategory>
   <PreferenceCategory app:title="@string/sync_header">
      <SwitchPreferenceCompat
         app:key="sync"
         app:title="@string/sync_title" />
      <SwitchPreferenceCompat
         app:dependency="sync"
         app:key="attachment"
         app:summaryOff="@string/attachment_summary_off"
         app:summaryOn="@string/attachment_summary_on"
         app:title="@string/attachment_title" />
   </PreferenceCategory>
</PreferenceScreen>

Step 5 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity
         android:name=".MainActivity"
         android:label="@string/title_activity_settings">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Play Icon  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code

raja
Published on 23-Oct-2019 07:57:18
Advertisements