我正在尝试以编程方式在DrawerLayout中创建一个ActionBar,如下所示:
import android.support.v7.widget.Toolbar;
public class RevToolBar extends MainActivity {
public Toolbar getRevToolbar() {
Toolbar revToolBar = new Toolbar( this );
setSupportActionBar(revToolBar);
return revToolBar;
}
}
然后在主要活动中:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = new RevToolBar().getRevToolbar();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
然而,应用程序在启动后总是崩溃:
App停止了 再次打开应用
使用Java创建ActionBar / Toolbar并将其添加到DrawerLayout的正确方法是什么?
提前谢谢大家。
更新
输出抛出:
07/10 14:16:22: Launching app
$ adb install-multiple -r -p com.example.rev.myapp /media/rev/5431214957EBF5D7/projects/android/myapp/app/build/intermediates/split-apk/debug/slices/slice_0.apk
Split APKs installed
$ adb shell am start -n "com.example.rev.myapp/com.example.rev.myapp.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 9754 on device Nexus_5X_Edited_API_25 [emulator-5554]
Application terminated.
答案 0 :(得分:1)
试试这个
public class RevToolBar
{
Context mContext;
public RevToolBar(Context context){
mContext = context;
}
public Toolbar getRevToolbar() {
Toolbar toolbar = new Toolbar(mContext);
LinearLayout.LayoutParams toolBarParams = new LinearLayout.LayoutParams(
Toolbar.LayoutParams.MATCH_PARENT,
150
);
toolbar.setLayoutParams(toolBarParams);
toolbar.setBackgroundColor(Color.BLUE);
toolbar.setVisibility(View.VISIBLE);
return toolbar;
}
}
并在MainActivity中
RevToolBar revToolBar = new RevToolBar(MainActivity.this);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer .addView(revToolBar.getRevToolbar(), 0);