Reputation: 6624
I'm trying to programatically create an ActionBar in a DrawerLayout as follows:
import android.support.v7.widget.Toolbar;
public class RevToolBar extends MainActivity {
public Toolbar getRevToolbar() {
Toolbar revToolBar = new Toolbar( this );
setSupportActionBar(revToolBar);
return revToolBar;
}
}
Then in the main activity:
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);
}
However, the app always crashes just after starting:
App has stopped
Open app again
What is the proper way to create and add an ActionBar/ Toolbar in Java to a DrawerLayout?
Thank you all in advance.
UPDATE
The output thrown:
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.
Upvotes: 0
Views: 144
Reputation: 357
try this
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;
}
}
and in MainActivity
RevToolBar revToolBar = new RevToolBar(MainActivity.this);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer .addView(revToolBar.getRevToolbar(), 0);
Upvotes: 1