在我的SettingsActivity extends AppCompatActivity
内{我有} SettingsFragment extends PreferenceFragment
。当我尝试在工具栏中按home-buttion时它不起作用。这是我的代码
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/settingsToolbar"
android:layout_width="match_parent"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_height="?android:actionBarSize"
android:background="@color/colorPrimary" />
SettingsActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupToolBar();
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
private void setupToolBar() {
getLayoutInflater().inflate(R.layout.toolbar, (ViewGroup) findViewById(android.R.id.content));
Toolbar toolbar = (Toolbar) findViewById(R.id.settingsToolbar);
setSupportActionBar(toolbar);
setTitle(getResources().getString(R.string.settings));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setFocusable(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
我试图以这种方式解决它:删除setNavigationOnClickListener
并添加:
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return (super.onOptionsItemSelected(menuItem));
}
没有用。我该如何解决这个问题?
答案 0 :(得分:0)
添加此行以配置您的getSupportActionBar:
getSupportActionBar().setHomeButtonEnabled(true);
在您的活动中使用这两个代码,如下所示:
你的setupToolbar方法中的:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Log.d("cek", "home selected");
finish();
}
});
并在你的onOptionsItemSelected方法中:
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);