我使用this指南为我的应用构建了一个设置活动/屏幕。示例代码如下。 我错过了能够在这个新活动中添加一个工具栏并在其左侧放置一个后退箭头?
的AndroidManifest.xml
....
<activity
android:name=".SettingsActivity"
android:label="Settings"
android:launchMode="singleTask"
android:theme="@style/AppTheme.NoActionBar"/>
....
的preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="pref_sync"
android:title="@string/pref_sync"
android:summary="@string/pref_sync_summ"
android:defaultValue="true" />
<ListPreference
android:dependency="pref_sync"
android:key="pref_syncConnectionType"
android:title="@string/pref_syncConnectionType"
android:dialogTitle="@string/pref_syncConnectionType"
android:entries="@array/pref_syncConnectionTypes_entries"
android:entryValues="@array/pref_syncConnectionTypes_values"
android:defaultValue="@string/pref_syncConnectionTypes_default" />
</PreferenceScreen>
SettingsFragment.java
public static class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
...
}
SettingsActivity.java
public class SettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}
答案 0 :(得分:7)
您必须在活动布局中包含工具栏。例如:
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.SettingsActivity">
<include
android:id="@+id/app_bar"
layout="@layout/app_bar" />
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/app_bar"/>
</RelativeLayout>
app_bar.xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
在您的Activity.onCreate()中获取工具栏并设置主页按钮(小箭头):
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
将SettingsActivity设置为父MainActivity的子级:
<activity
android:name=".activities.SettingsActivity"
android:label="@string/title_activity_main"
android:parentActivityName=".activities.MainActivity" />
这会给你那个小箭头。
另外,这样做:
public class SettingsActivity extends AppCompatActivity
不是这个:
public class SettingsActivity extends Activity
为了使用支持库。