我想在扩展FragmentActivity 的 Activity 上设置工具栏。我知道为了使用 setSuppoertActionBar(toolbar)
方法,我们扩展了 AppCompatActivity
而不是 FragmentActivity
但我覆盖了 onMenuItemSelected(int featureId, MenuItem item)
方法在 AppCompatActivity
中是 final 并且 final 方法不能覆盖。所以我只能扩展 FragmentActivity
。
这是我的代码:
public class MainActivity extends FragmentActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar); -> error is here
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()){
case R.id.action_search:
onSearchRequested();
break;
}
return super.onMenuItemSelected(featureId, item);
}
我看到很多与该问题相关的答案,但每个人都说扩展 AppCompatActivity
而不是 FragmentActivity
但我想设置工具栏以及覆盖 onMenuItemSelected(int featureId , MenuItem 项)
方法。
我该怎么办,求助
最佳答案
当你使用NavigationDrawer
这个东西很好
使用这个:-
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
然后在 onNavigationItemSelected
中根据不同的 fragment 设置不同的 Toolbar Title :-
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
sfm = getSupportFragmentManager();
Fragment fragment = new Fragment();
int id = item.getItemId();
if (id == R.id.nav_id) {
fragment = new YourFragment();
toolbar.setTitle("SET TOOLBAR NAME");
}else if (id == R.id.nav_id2) {
fragment = new YourFragment();
toolbar.setTitle("SET TOOLBAR NAME");
}
对于单个 fragment ,首先像这样自定义您的 style.xml
:-
<style name="YourStyleName" parent="Theme.AppCompat.Light.DarkActionBar">
// ToDo as you want to do or as per your requirement
</style>
然后应用到您的自定义工具栏
:-
<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/YourStyleName" >
// ...........
</android.support.v7.widget.Toolbar>
关于android - 如何在 FragmentActivity 上设置工具栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34870245/