java - 如何将工具栏添加到 PreferenceActivity

标签 java android

我正在创建一个应用程序,该应用程序具有带操作栏的设置 PreferenceActivity,并且运行良好。我想将另一个自定义 PreferenceActivity 与 actionbar 一起使用,它使用布局 (activity_about.xml) 和首选项布局 (about_preferences.xml)。但是当我运行该应用程序时,它会导致我的应用程序在调用该 Activity 时崩溃。可能操作栏正在返回 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

最佳答案

将 ID 添加到您的工具栏:

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

并在调用 getSupportActionBar() 之前调用 setSupportActionBar()(传递您的 Toolbar 实例):

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

关于java - 如何将工具栏添加到 PreferenceActivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47095809/

相关文章:

Android 后退按钮导航到特定 fragment

android - “setup”已被弃用,不应使用。使用购买配置

java - 线程 "main"java.lang.NoClassDefFoundError : org/opencv/core/Core 中的异常

c# - x.toString() 和 x +""之间的区别

java - JDBC Hibernate - Mysql 连接错误

android - 在 Android 中,为什么我需要为 "test"sourceSet 使用 androidTestCompile?

java - 使用合作伙伴 WSDL 连接到 SFDC 的测试实例

java - Json数据数组请求不断跳过onResponse

java - android中变量的全局声明

android - 创建android项目时无法写入jarlist缓存文件