Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a button to PreferenceScreen

Is there any way to add a button to the bottom of preferences screen and make them work correct when scrolling?

like image 665
vlaku Avatar asked Apr 23 '10 08:04

vlaku


People also ask

How to add button in Preference activity?

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.

What is PreferenceScreen in Android?

Use the AndroidX Preference Library for consistent behavior across all devices. For more information on using the AndroidX Preference Library see Settings. Represents a top-level Preference that is the root of a Preference hierarchy. A PreferenceActivity points to an instance of this class to show the preferences.


2 Answers

There is another solution for customizing the appearance of the preferences.

Design a normal XML layout with buttons or whatever you want to add to the standard preferences. Include a ListView in your layout and give it the ID @android:id/list.

Let's say we call the layout file res/layout/main.xml. It could look something like this:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"               android:layout_width="match_parent"               android:layout_height="match_parent"               android:orientation="vertical">     <Button android:text="This is a button on top of all preferences."             android:layout_width="wrap_content"             android:layout_height="wrap_content" />     <ListView android:id="@android:id/list"               android:layout_width="match_parent"               android:layout_height="wrap_content" /> </LinearLayout> 

In your PreferenceActivity, add these two lines to your onCreate:

addPreferencesFromResource(R.xml.preferences); setContentView(R.layout.main); 

The ListView in your layout will then be replaced by the preferences defined the usual way in res/xml/preferences.xml.

like image 80
Max Avatar answered Sep 25 '22 14:09

Max


I know this is a bit late, but I just found a solution i like better than Max's praised solution.

You can simply add a footer (or if you like the button to be on top, a header) to the PreferenceActivity's ListView like so:

public class MyActivity extends PreferenceActivity {     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         addPreferencesFromResource(R.xml.preferences);         ListView v = getListView();         v.addFooterView(new Button(this));     } } 

I hope this helps someone.

like image 40
jpihl Avatar answered Sep 25 '22 14:09

jpihl