简体   繁体   中英

How to add Toolbar to PreferenceActivity

I am creating an app which have a setting PreferenceActivity with actionbar and that's working fine. I want to use another custom PreferenceActivity with actionbar which is using a layout (activity_about.xml) and preference layout (about_preferences.xml). But when i run the app it's causing my app to crash on calling that activity. Probably the actionbar is returning the Null, i can't figure it out where is the problem. Please help.

My ActivityAbout.java

public class ActivityAbout  extends PreferenceActivity {

private AppCompatDelegate mDelegate;
private ActionBar actionBar;
private SharedPref sharedPref;
private View parent_view;
private TextView ver;
Context context=this;


@Override
protected void onCreate(Bundle savedInstanceState) {
    getDelegate().installViewFactory();
    getDelegate().onCreate(savedInstanceState);
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.about_preferences);
    setContentView(R.layout.activity_about);
    View lv = findViewById(android.R.id.list);
    if (lv != null) lv.setPadding(0, 0, 0, 0);


    final Preference prefPrivacy = (Preference) findPreference(getString(R.string.pref_title_privacy));
    final Preference prefTerm = (Preference) findPreference(getString(R.string.pref_title_term));
    final Preference prefBuild = (Preference) findPreference(getString(R.string.pref_title_build));
    final Preference prefCopyright = (Preference) findPreference(getString(R.string.pref_title_copyright));



    String versionName = BuildConfig.VERSION_NAME;

    ver = (TextView) findViewById(R.id.version);
    ver.setText("Version "+versionName);

    prefBuild.setSummary("Version "+versionName);

    int y = Calendar.getInstance().get(Calendar.YEAR);
    prefCopyright.setSummary("Copyright © "+y+" Get Rid Remedy.\nAll Right Reserved.");


    prefPrivacy.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            dialogPrivacy(ActivityAbout.this);
            return false;
        }
    });

    prefTerm.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            dialogTerm(ActivityAbout.this);
            return false;
        }
    });

    initToolbar();

}

public void dialogPrivacy(Activity activity) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(activity.getString(R.string.pref_title_privacy));
    builder.setMessage(activity.getString(R.string.content_privacy));
    builder.setPositiveButton("OK", null);
    builder.show();
}

public void dialogTerm(Activity activity) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(activity.getString(R.string.pref_title_term));
    builder.setMessage(activity.getString(R.string.content_term));
    builder.setPositiveButton("OK", null);
    builder.show();
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    getDelegate().onPostCreate(savedInstanceState);
}

    private void initToolbar() {
        actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        actionBar.setTitle(R.string.activity_title_settings);
    }



@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        onBackPressed();
    }
    return super.onOptionsItemSelected(item);
}


public ActionBar getSupportActionBar() {
    return getDelegate().getSupportActionBar();
}

public void setSupportActionBar(@Nullable Toolbar toolbar) {
    getDelegate().setSupportActionBar(toolbar);
}

@Override
public MenuInflater getMenuInflater() {
    return getDelegate().getMenuInflater();
}

@Override
public void setContentView(@LayoutRes int layoutResID) {
    getDelegate().setContentView(layoutResID);
}

@Override
public void setContentView(View view) {
    getDelegate().setContentView(view);
}

@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
    getDelegate().setContentView(view, params);
}

@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
    getDelegate().addContentView(view, params);
}

@Override
protected void onPostResume() {
    super.onPostResume();
    getDelegate().onPostResume();
}

@Override
protected void onTitleChanged(CharSequence title, int color) {
    super.onTitleChanged(title, color);
    getDelegate().setTitle(title);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    getDelegate().onConfigurationChanged(newConfig);
}

@Override
protected void onStop() {
    super.onStop();
    getDelegate().onStop();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    getDelegate().onDestroy();
}

public void invalidateOptionsMenu() {
    getDelegate().invalidateOptionsMenu();
}

private AppCompatDelegate getDelegate() {
    if (mDelegate == null) {
        mDelegate = AppCompatDelegate.create(this, null);
    }
    return mDelegate;
}

}

Here is the about_preferences layout.

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <Preference
        android:key="@string/pref_title_dev_email"
        android:summary="@string/developer_email"
        android:title="@string/pref_title_dev_email"/>
    <Preference
        android:key="@string/pref_title_copyright"
        android:summary="@string/copyright"
        android:title="@string/pref_title_copyright"/>
    <Preference
        android:key="@string/pref_title_build"
        android:summary="@string/app_version"
        android:title="@string/pref_title_build"/>
    <Preference
        android:key="@string/pref_title_privacy"
        android:title="@string/pref_title_privacy"
        android:widgetLayout="@layout/ic_about"/>
    <Preference
        android:key="@string/pref_title_term"
        android:title="@string/pref_title_term"
        android:widgetLayout="@layout/ic_about"/>

Here is activity_about.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/activity_about"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.overridecode.getridremedy.ActivityAbout">

<android.support.design.widget.AppBarLayout
    android:id="@+id/tool"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <include layout="@layout/toolbar" />

</android.support.design.widget.AppBarLayout>

<LinearLayout
    android:layout_below="@+id/tool"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/activity_vertical_margin">

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="center"
        app:srcCompat="@mipmap/ic_launcher"
        android:id="@+id/imageView" />

    <TextView
        android:text="@string/app_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:textSize="30dp"
        android:textStyle="bold"
        android:textColor="#73000000"
        android:id="@+id/app_title" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:id="@+id/version" />

</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_alignParentBottom="true">

    <ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

The error i am getting:

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.overridecode.getridremedy/
com.overridecode.getridremedy.ActivityAbout}: 
java.lang.NullPointerException: Attempt to invoke virtual method 'void 
android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference

Add an ID to your Toolbar :

<include
    android:id="@+id/toolbar_prefs"
    layout="@layout/toolbar" />

And call setSupportActionBar() (passing your Toolbar instance) before calling getSupportActionBar() :

private void initToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_prefs);
    setSupportActionBar(toolbar);        

    actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);
    actionBar.setTitle(R.string.activity_title_settings);
}

Otherwise getSupportActionBar() will return null .

As per my experience, I found there is no ActionBar in preference activity. So, There are following steps to add toolbar in your activity

Add in xml

<include layout="@layout/toolbar" />

Set Toolbar in java class using following code.

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarId);
setSupportActionBar(toolbar);      

NOTE : here you need to use this code in starting of intitToolbar() method.

Import proper class/package for your toolbar. From your comments seems you need to import

import android.support.v7.widget.Toolbar;

Hope this may help you. If helps, please approve it as right answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM