我想设置toolbar关于我的活动延伸片段活动。我知道用于使用setSuppoertActionBar(toolbar)
我们扩展的方法AppCompatActivity
代替FragmentActivity
但我重写了onMenuItemSelected(int featureId, MenuItem item)
最终的方法是AppCompatActivity
最终方法不能重写。所以我只能扩展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 item)
method.
我该怎么办,请帮忙。
这个东西在你使用的时候很好用NavigationDrawer
use this:-
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
然后根据不同的fragment设置Toolbar Title,在中设置不同的TitleonNavigationItemSelected
:-
@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");
}
对于单个片段,首先自定义您的style.xml
像这样 :-
<style name="YourStyleName" parent="Theme.AppCompat.Light.DarkActionBar">
// ToDo as you want to do or as per your requirement
</style>
然后应用到您的自定义中toolbar
:-
<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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)