I have been flowing this tutorial by android,
https://developer.android.com/training/implementing-navigation/lateral.html
and i cannot add tabs to the action bar,
i get an error saying
Attempt to invoke virtual method 'void android.app.ActionBar.setNavigationMode(int)' on a null object reference
I read somewhere the tabs are not supported anymore,
I have resolved to using the Title Strip instead in the same tutorial wich works, great, but i prefer the tabs,
what am i making wrong ?
here is my fragment activity,
package apps.radwin.wintouch.activities.alignmentActivities;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import apps.radwin.wintouch.R;
import apps.radwin.wintouch.adapters.aligmentAdapters.SwipeAdapterProjectSelection;
public class projectSelectionMainFragment extends FragmentActivity
implements NavigationView.OnNavigationItemSelectedListener {
ViewPager mainViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project_selection_main_fragment);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
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);
/////////////////////////////////////////
//////// Start Of Implementation ////////
/////////////////////////////////////////
mainViewPager = (ViewPager) findViewById(R.id.projectSelectionMainViewPager); // the main view pager
SwipeAdapterProjectSelection swipeAdapter = new SwipeAdapterProjectSelection(getSupportFragmentManager()); // calls the adapter and initlizes it
mainViewPager.setAdapter(swipeAdapter); // sets the adapter
///////////////////////////////////////////
/////start of action bar implementation////
///////////////////////////////////////////
final ActionBar actionBar = getActionBar();
// Specify that tabs should be displayed in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create a tab listener that is called when the user changes tabs.
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// hide the given tab
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// probably ignore this event
}
};
// Add 3 tabs, specifying the tab's text and TabListener
for (int i = 0; i < 3; i++) {
actionBar.addTab(
actionBar.newTab()
.setText("Tab " + (i + 1))
.setTabListener(tabListener));
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.project_selection_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
error log:
Process: apps.radwin.wintouch, PID: 32161
java.lang.RuntimeException: Unable to start activity ComponentInfo{apps.radwin.wintouch/apps.radwin.wintouch.activities.alignmentActivities.projectSelectionMainFragment}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setNavigationMode(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setNavigationMode(int)' on a null object reference
at apps.radwin.wintouch.activities.alignmentActivities.projectSelectionMainFragment.onCreate(projectSelectionMainFragment.java:74)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
build gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "apps.radwin.wintouch"
minSdkVersion 19
targetSdkVersion 23
versionCode 21
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
jcenter()
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile files('libs/core.jar')
provided 'org.glassfish:javax.annotation:10.0-b28'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.google.android.gms:play-services-appindexing:8.4.0'
compile 'com.github.ybq:Android-SpinKit:1.0.4'
compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.1'
compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'
compile 'com.rengwuxian.materialedittext:library:2.1.4'
compile 'com.github.fenjuly:ArrowDownloadButton:9e15b85e8a'
compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
compile 'com.yayandroid:LocationManager:1.1.1'
compile 'com.google.android.gms:play-services-location:7.5.0'
compile 'com.github.quentin7b:android-location-tracker:3.2'
compile 'com.github.lzyzsd:circleprogress:1.1.0#aar'
compile 'com.android.support:support-v4:23.4.0'
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
}
After
final ActionBar actionBar = getActionBar();
set
setSupportActionBar(actionBar);
EDIT: yea i miss
setSupportActionBar(toolbar);
after u initialize toolbar
First set Toolbar as action bar
setSupportActionBar(toolbar);
Instead of
final ActionBar actionBar = getActionBar();
Please use
final ActionBar actionBar = getSupportActionBar();
Also make sure intheme/style that you have mentioned
windowActionBar as true or in activity
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
You should extend AppCompatActivity instead of extending FragmentActivity because AppCompatActivity inherits from FragmentActivity and you need to set your Toolbar as your ActionBar. also make sure your base themes parent is AppCompat.Light.NoActionBar something like this
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
and include
setSupportActionBar(toolbar);
after
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
and get reference with getSupportActionBar(); not getActionBar();
Answered, by removing the old Action bar Implementation and inserting the new
Tabllayout implementation as stated by android,
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabsLayoutWorkorderSelection);
tabLayout.setupWithViewPager(mainViewPager);
as it is implemented in the new tabbed activity you can do when you open a new Activity in Android.
in that case the Class can extends AppCompatActivity instead of FragmentActivity.
Related
This question already has answers here:
NavigationView OnNavigationItemSelectedListener not being called
(3 answers)
Closed 4 years ago.
I created the Activity with the Wizard.
I deleted what I am not interested in, for example, the floating action button.
Created my custom items in the activity_main_drawer.xml
The wizard created the onNavigationItemSelected function (see code below) and I added my code so it quits the activity and goes back to the Login Screen.
So I don't know why, I see nothing interesting in the logcat so this is a logical problem. I am a newbie and Navigation View scares me a lot... Let me know if I missed anything you need.
package com.skrefi.googleplaycopy;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
//Don't know what this is
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//Don't know what this is either
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//In case I need it for the admin activity >> the 3 dots pop down thingy <<
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
MakeToast("SOMETHING");
switch (item.getItemId()){
case R.id.action_settings:
MakeToast("Settings button clicked");
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch(item.getItemId()){
case R.id.item_signout:
firebaseAuth.getInstance().signOut();
MakeToast("Signed out!");
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
break;
}
//DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawer.closeDrawer(GravityCompat.START);
return true;
}
public void MakeToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
}
Edit:
So it may be confusing if I set the visibility to gone and I get use the layout I want right in this layout file because I get the screen without the toolbar, this is what I want. AND I want to keep that as well for the admin part, to check later in if the user is me, and if so, I get a new item in the drawer called Admin Activity which simply set the thingy visibility to visible so i get the admin screen.
Here is what you (#) asked for:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!--This is for a potential admin screen-->
<include
android:id="#+id/include_toolbar_with_threedots_settings"
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is for test"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</android.support.v4.widget.DrawerLayout>
You're calling finish() before actually starting your activity while you should call it after starting your login activity. The following code will start Login activity and close the Main activity.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch(item.getItemId()){
case R.id.item_signout:
firebaseAuth.getInstance().signOut();
MakeToast("Signed out!");
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
break;
}
//DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawer.closeDrawer(GravityCompat.START);
return true;
}
I know there are many equal to the problems but none of the many who have read is equal to mine or has worked for me for help , so it is going to require your help.
I'm working on an application with a NavigationDrawer , I need to make an image work for me on and off the bluetooth cell .
I made another code separately with an " empty activity" and if I worked, but in the navigariondrawe that is where I need it to work , but it does not work , I 've tried many things , but I hope you can help me .
FATAL EXCEPTION: main
Process: com.example.lab02pc19.myapplication2, PID: 5146
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lab02pc19.myapplication2/com.example.lab02pc19.myapplication2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.example.lab02pc19.myapplication2.MainActivity.setImagenBluetooth(MainActivity.java:69)
at com.example.lab02pc19.myapplication2.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6245)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lab02pc19.myapplication2">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
package com.example.lab02pc19.myapplication2;
import android.bluetooth.BluetoothAdapter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, FragmentBlue.OnFragmentInteractionListener {
ImageView miimagen;
BluetoothAdapter adaptador_bluetooth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
miimagen= (ImageView)findViewById(R.id.ivw);
adaptador_bluetooth= BluetoothAdapter.getDefaultAdapter();
if(adaptador_bluetooth==null)
{
miimagen.setVisibility(View.GONE);
}
else
{
setImagenBluetooth(adaptador_bluetooth.isEnabled());
}
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);
}
public void clickImagen(View view)
{
switch (view.getId())
{
case R.id.ivw:
setEstadoBluetooth();
break;
}
}
public void miimagen()
{
setEstadoBluetooth();
}
public void setImagenBluetooth(boolean valor)
{
if(valor)miimagen.setImageResource(R.drawable.ic_action_bluetooth);
}
public void setEstadoBluetooth()
{
if(adaptador_bluetooth.isEnabled())
{
setImagenBluetooth(false);
adaptador_bluetooth.disable();
}
else
{
setImagenBluetooth(true);
adaptador_bluetooth.enable();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
boolean FragmenTransaction= false;
Fragment fragment = null;
if (id == R.id.nav_camera) {
fragment = new FragmentBlue();
FragmenTransaction= true;
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
if(FragmenTransaction)
{
getSupportFragmentManager().beginTransaction().replace(R.id.content_main,fragment).commit();
item.setChecked(true);
getSupportActionBar().setTitle(item.getTitle());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.lab02pc19.myapplication2.FragmentBlue">
<!-- TODO: Update blank fragment layout -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivw"
android:layout_gravity="left|top"
android:background="#drawable/ic_action_bluetooth"
android:clickable="true"
android:onClick="clickImagen"
android:contentDescription="#string/imagen" />
</FrameLayout>
As I think (it is not enough info), you want to create a fragment in the activity and make some actions with ImageView further. But you didn't create the fragment and try to find ImageView by id in other layout - thus, the image view didn't exist here, next you try to call function of the null object and finally have a NPE and crash. You need to read tutorial about fragment in Android: https://developer.android.com/training/basics/fragments/index.html
You are trying to access the image view of the fragment in your activity class which is not possible that's why giving null point exception. What you can do it that you can setImage in the image view in you fragment java class in onActivityCreated override method after setting the contentView.
If you want to set the image from the activity only then you can create the public method in the fragment and call the method from the activity.
I am using a template navigation drawer that was provided by android studio. I am very new to android development so i'm wondering if i'm missing something simple here. I want to start a new activity by clicking on an item in my navigation menu I followed several tutorials on how to do this but i keep getting this error in my logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsmyth.sidemenu/com.example.bsmyth.sidemenu.second_activity}: java.lang.NullPointerException
Here is the code I tried to start a new activity:
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
}
else if (id == R.id.nav_gallery) {
Intent intent = new Intent(MainActivity.this, second_activity.class);
startActivity(intent);
}
else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I referred to my second activity in my manifest file like this:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".second_activity">
<intent-filter>
<action android:name="com.example.bsmyth.sidemenu.second_activity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Here is the drawer layout:
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_camera"
android:icon="#drawable/ic_menu_camera"
android:title="Adfeed"
android:checked="true"/>
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="Post" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="Notification" />
<item
android:id="#+id/nav_manage"
android:icon="#drawable/ic_menu_send"
android:title="Messages" />
</group>
Here is the second activity:
package com.example.bsmyth.sidemenu;
import android.app.ActionBar;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class second_activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is second_activity layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
And here are the error messages in logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsmyth.sidemenu/com.example.bsmyth.sidemenu.second_activity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.bsmyth.sidemenu.second_activity.onCreate(second_activity.java:30)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Your second activity layout has only a DrawerLayout and one TextView it does not have the views that you are calling in onCreate method.
Try running it again after removing this views from your onCreate:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
add this:
android:id="#+id/drawer_layout"
to your DrawerLayout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
Use a little common sense on these, you are using findViewById for drawer_layout, toolbar as well as nav_view and other extras too.
But there is nothing in second_activity layout except one TextView even that is without any id. Then how can these codes work ?
Create these elements like shown in new android project in android studio then follow the same pattern and see how the next layout is included there.
Your will get multiple NullPointerException in your code. You only copied the code of MainActivity.java to second_activity.java but not in the layout file from activity_main to second_activity.
You can create your second activity in project explorer and selecting the activity you want from the template. It is the easiest way and also very good way. After that you can simply call the second activity from first activity like you are doing now
You are doing many things wrong in second activity code....
In layout XML..you don't give any id for drawer layout which you are using (drawer_layout).
So Add this...
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
Also create this view toolbar and nav_view in this XML file like you have create Textview in second_activity XML .
And create Drawer object only once with same drwaer id(drawer_layout).
Like...
//declare this globally(means out of any method)
DrawerLayout drawer;
and then initialize this in onCreate method...
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
and at last remove this line DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); from onBackPressed() and onNavigationItemSelected method.
Hope this will help you...
Hello I am new to android, I am currently trying to navigate from my MainActivity to a TabbedActivity. I created a new TabbedActivity using the default Tabbed Activity template in the Gallery in Android Studio.
However after the files were created, I checked the code and saw that many lines of code used in creating the Activity were cross out, meaning they were deprecated.
I tried running the app, it worked until I tried to navigate to this Tabbed Activity then it crashed and threw an error in my Android Monitor.
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxxxx.eventmanager/com.xxxxxx.eventmanager.EventDetailsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.xxxxxx.eventmanager.EventDetailsActivity.onCreate(EventDetailsActivity.java:42)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is my Tabbed Activity named EventDetailsActivity. I have not added any custom code or made any changes to the default code that was generated on create:
package com.xxxxxx.eventmanager;
import android.app.Activity;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class EventDetailsActivity extends Activity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_details);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_event_details, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_event_details, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
I am new to both Java and Android and quite perplexed by this.
try to change this line
final ActionBar actionBar = getActionBar();
TO
final ActionBar actionBar = getSupportActionBar();
use extends AppCompatActivity and use use the toolbar as..
private void setup_tabs(){
pager = (CustomViewPager)findViewById(R.id.viewpager);
pager.setOffscreenPageLimit(3);
adapter = new Tabs_Pager_adapter(getSupportFragmentManager(),this);
pager.setAdapter(adapter);
pager.setPagingEnabled(true);
// Title.setText(adapter.getPageTitle(pager.getCurrentItem()));
tabLayout = (TabLayout) findViewById(R.id.tabs);
// tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Respondents"));
tabLayout.addTab(tabLayout.newTab().setText("History"));
tabLayout.setupWithViewPager(pager);
}
private void setupToolbar(){
toolbar = (Toolbar) findViewById(R.id.toolbar);
if(toolbar != null)
setSupportActionBar(toolbar);
// Show menu icon
final ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setDisplayShowTitleEnabled(false);
toolbar.setNavigationIcon(R.drawable.ic_action_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
And in your layout..
<LinearLayout
android:layout_weight=".75"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical" >
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed"/>
<your.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And this the theme..
<style name="Base.Theme.your_theme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/my_primary</item>
<item name="colorPrimaryDark">#color/my_primary_dark</item>
<item name="colorAccent">#color/my_accent</item>
</style>
Use the app compat library with android support library... and with design support library.. it is awesome. use the tooolbar layout in your layout.xml
and set the theme with appcompat with no actionbar.
How I treat with toolbar in my app (for example).
In my activity layout xml file:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<!-- more xml code below -->
Content of toolbat.xml:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar_actionbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/PopupMenuStyle"
android:background="#color/bar_color">
<!-- arbitrary components are in toolbar -->
</android.support.v7.widget.Toolbar>
Now I prepared for set up the toolbar in my app. In onCreate method I have to use this code before using toolbar:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
Since that moment I can use getSupportActionBar() and it will return correct result.
In your case you may use setActionBar(toolbar) instead of setSupportActionBar(toolbar) and <android.widget.Toolbar instead of <android.support.v7.widget.Toolbar in your layout file.
I am trying to use the android navigation drawer with the action bar of AppCompatActivity. But when I implement the action bar the icon to open the navigation drawer is missing in it.
This is what I want to be displayed
This is a screenshot of my current action bar
You can see my code below.
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/action_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"/>
<!--app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_view" />-->
</android.support.v4.widget.DrawerLayout>
This is my action_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.Toolbar>
This is my MainActivity
package com.blog.waiyanhein.llks.llks;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Why is the icon to open the navigation drawer missing using my code?
You didn't implement the NavigationDrawer in your Activityi guess.i've had the same problem and that fixed with the following code.
In your Activity:
private DrawerLayout drawerLayout;
In your onCreate:
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.home:
drawerLayout.closeDrawers();
return true;
default:
return true;
}
}
});
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle =
new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
Strings.xml:
<string name="openDrawer">Navigation</string>
<string name="closeDrawer">Close Navigation</string>
Then it should work.
Try this code,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
You may need to include:
actionBarDrawerToggle.syncState();
The answer here may help:
Appcompatv7 - v21 Navigation drawer not showing hamburger icon