如何将工具栏添加到PreferenceActivity

时间:2017-11-03 12:26:37

标签: java android

我正在创建一个应用程序,其中设置了带有操作栏的PreferenceActivity,并且工作正常。我想使用另一个自定义PreferenceActivity和actionbar,它使用布局(activity_about.xml)和首选项布局(about_preferences.xml)。但是当我运行应用程序时,它会导致我的应用程序在调用该活动时崩溃。可能行动栏正在返回Null,我无法弄清楚问题出在哪里。请帮忙。

我的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;
}

}

这是about_preferences布局。

<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"/>

这是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>

我得到的错误:

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

2 个答案:

答案 0 :(得分:0)

为您的Toolbar添加ID:

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

在致电setSupportActionBar()之前致电Toolbar(传递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);
}

否则getSupportActionBar()将返回null

答案 1 :(得分:0)

根据我的经验,我发现偏好活动中没有ActionBar。所以, 在您的活动中添加工具栏有以下步骤

添加xml

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

使用以下代码在java类中设置Toolbar

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

注意:在此处,您需要在启动intitToolbar()方法时使用此代码。

导入工具栏的正确类/包。您的评论似乎需要导入

import android.support.v7.widget.Toolbar;

希望这可以帮到你。如果有帮助,请批准为正确答案。