Custom views in a PreferenceActivity


SDK Version: 
M3

Let's take another look at PreferenceAcitivites, and how we can use other views, than the basic PreferenceActivity views.

I'm using a very simple layout here, but you could do anything you would do in a normal acitivty. The only necessary view is a listview, with the id: android:id="@android:id/list".

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.         android:orientation="vertical" android:layout_width="fill_parent"
  4.         android:layout_height="fill_parent" android:weightSum="1">
  5.         <ListView android:id="@android:id/list" android:layout_width="fill_parent"
  6.                 android:layout_height="200dip"></ListView>
  7.         <android.webkit.WebView android:id="@+id/webView1"
  8.                 android:layout_width="fill_parent" android:layout_height="fill_parent"></android.webkit.WebView>
  9. </LinearLayout>

screenshot

And here is the PreferenceActivity:

  1. public class CustomPrefActivityActivity extends PreferenceActivity {
  2.  
  3.         @Override
  4.         protected void onCreate(Bundle savedInstanceState) {
  5.                 super.onCreate(savedInstanceState);
  6.                 setContentView(R.layout.main); //set the contentview. On the layout, you need a listview with the id: @android:id/list
  7.                
  8.                 //you could also make a new listview here, and set the id to android.R.id.list, so you don't have to use xml layouts.
  9.  
  10.                 addPreferencesFromResource(R.xml.settings); //load preferences from xml, or create preferences by code here
  11.                
  12.                 //setup any other views that you have
  13.                 WebView webView = (WebView) findViewById(R.id.webView1);
  14.                 webView.setWebViewClient(new WebViewClient());
  15.                 webView.loadUrl("http://helloandroid.com&quot;);
  16.         }
  17. }

This is useful, when you want to use the ready made Preferences, to keep the default Android look, but want to add some more functionality to your settings screen.
I guess it's worth mentioning that the addPreferencesFromResource() method is deprecated, and in the future, the preferred method would be to use PreferenceFragments.