AndroidRuntime shutting down Fatal Exception: main Android Studio 2.2 - android

working on an app and ran into a problem only when I run it on a phone.
Here is the Run info:
09/24 21:02:00: Launching app
Cold swapped changes.
$ adb shell am start -n "com.example.crow.page3/com.example.crow.page3.Page3main" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Connected to process 1154 on device oneplus-a0001-793b4d36
I/art: Late-enabling -Xcheck:jni
W/System: ClassLoader referenced unknown path: /data/app/com.example.crow.page3-2/lib/arm
I/InstantRun: Instant Run Runtime started. Android package is com.example.crow.page3, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.example.crow.page3-2/lib/arm
I/LoadedApk: No resource references to update in package common
I/LoadedApk: No resource references to update in package com.blinq.theme.CleanUI.blue
I/LoadedApk: No resource references to update in package com.blinq.theme.CleanUI.blue
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.crow.page3, PID: 1154
Theme: themes:{default=overlay:com.blinq.theme.CleanUI.blue, iconPack:com.blinq.theme.CleanUI.blue, fontPkg:com.blinq.theme.CleanUI.blue, com.android.systemui=overlay:com.blinq.theme.CleanUI.blue, com.android.systemui.navbar=overlay:com.blinq.theme.CleanUI.blue}
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.crow.page3/com.example.crow.page3.Page3main}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TabHost.setup()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TabHost.setup()' on a null object reference
at com.example.crow.page3.Page3main.onCreate(Page3main.java:54)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5461) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
I/Process: Sending signal. PID: 1154 SIG: 9
Application terminated.
I have tried several things and been over the code multiple times. below is the code for com.example.crow.page3.Page3main:
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.EditText;
import android.widget.Button;
import android.widget.TabHost;
import android.app.Activity;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
public class Page3main extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
EditText nameTxt, phoneTxt, emailTxt, addressTxt;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//add new contact:--------------------------------------------------
setContentView(R.layout.activity_page3main);
nameTxt = (EditText) findViewById(R.id.txtName);
phoneTxt = (EditText) findViewById(R.id.txtPhone);
emailTxt = (EditText) findViewById(R.id.txtEmail);
addressTxt = (EditText) findViewById(R.id.txtAddress);
//define tabs for from add contact tabs
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
tabSpec.setContent(R.id.tabAddContact);
tabSpec.setIndicator("Creator");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("list");
tabSpec.setContent(R.id.tabContactList);
tabSpec.setIndicator("List");
tabHost.addTab(tabSpec);
final Button addBtn = (Button) findViewById(R.id.btnAdd);
//What happens on :
nameTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence s, int i, int i2, int i3) {
//check if there was input in the text
addBtn.setEnabled(!nameTxt.getText().toString().trim().isEmpty());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
//-------------------------------------------------------------------
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(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);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#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.page3main, 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();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_logbook) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new FirstFragmentLogbook()).commit();
} else if (id == R.id.nav_contacts) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new SecondFragmentContacts()).commit();
} else if (id == R.id.nav_map) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new ThirdFragmentMap()).commit();
} else if (id == R.id.nav_site_info) {
} 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;
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Page3main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
Any ideas would be greatly appreciated. Thanks
Layout code:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".Page3main"
android:orientation="vertical"
android:baselineAligned="false"
android:weightSum="1">
<TabHost
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/tabHost"
android:layout_gravity="left|center_vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/tabContactList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView3"
android:textAppearance="#android:style/TextAppearance.Material.Large"
android:layout_margin="10dp"
android:layout_gravity="center"
android:textAlignment="center" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/tabAddContact"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lblCreatorTitle"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="New Contact"
android:layout_margin="10dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/txtName"
android:hint="Name"
android:inputType="textPersonName"
android:layout_gravity="center"
android:layout_weight="0.10"
android:drawableStart="#drawable/ic_contacts_black_24dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/txtPhone"
android:hint="Phone"
android:layout_gravity="center"
android:layout_weight="0.10"
android:drawableStart="#drawable/ic_call_black_24dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/txtEmail"
android:hint="Email"
android:layout_gravity="center"
android:layout_weight="0.10"
android:drawableStart="#drawable/ic_email_black_24dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/txtAddress"
android:hint="Address"
android:layout_gravity="center"
android:layout_weight="0.10"
android:drawableStart="#drawable/ic_place_black_24dp" />
<Button
android:text="Add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnAdd"
android:textAlignment="center"
android:layout_gravity="center" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>

As per your log you are getting a null pointer exception at android.widget.TabHost.setup()
The problem is probably in the following lines of code
//define tabs for from add contact tabs
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
In the above code the R.id.tabHost is returning a null pointer. Please check that you have this id defined in your layout. Also if you post the code where this ID is placed I could assist you further.
EDIT
Ok so the problem is you are calling setup method after you have loaded the tabs using findViewById. You must call setup method before loading tabs by findViewByid.
See the screenshot below of the developer documentation.
Here is the link to the documentation page. I hope this helps.

Related

Android App crashes on Button click

I have made a simple application which takes two numbers and add them but on button click my app crashes every time. I am new to android, Id really appreciate if someone can help me with this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ornadmin.myapplication.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="21dp"
android:layout_marginTop="29dp"
android:id="#+id/editText"
android:hint="number 1" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_below="#+id/editText"
android:layout_alignEnd="#+id/editText"
android:layout_marginTop="32dp"
android:id="#+id/editText2"
android:hint="number 2" />
<TextView
android:text="Result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="13dp"
android:id="#+id/textView"
android:layout_below="#+id/editText2"
android:layout_alignStart="#+id/editText2"
android:layout_marginTop="57dp"
android:textSize="30sp" />
<Button
android:text="sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="onButtonClick (MainActivity)"
android:layout_alignTop="#+id/textView"
android:layout_alignStart="#+id/textView"
android:layout_marginTop="97dp" />
</RelativeLayout>
Main Activity
package com.example.ornadmin.myapplication;
import android.app.Activity;
import android.app.IntentService;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends Activity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void onButtonClick(View v) {
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
TextView t1 = (TextView)findViewById(R.id.textView);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int sum = num1 + num2;
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
LOG
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ornadmin.myapplication, PID: 3812
java.lang.IllegalStateException: Could not find method onButtonClick (MainActivity)(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.Button with id 'button'
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4479)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4443)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Application terminated.
the problem is in this line
android:onClick="onButtonClick (MainActivity)"
the correction would be like this
android:onClick="onButtonClick"

NullPointerException When starting new Activity in Navigation Drawer

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...

issue with replacing Fragment views in Navigation drawer

I am using the android Navigation drawer template and fragments to display different views.
as the normal there is a MainActivity, activity_main.xml and content_main.xml generated automatically.
I have created two java classes; MusicFragment and MainFragment and of course the layout files which I have content inside.
When I run the app the activity_main is the default layout launched which I have welcome content displaying, I am using the Navigation drawer to navigate to my MusicFragment and MainFragment, this code I using to replace the current view in the onNavigationItemSelected method is;
if (id == R.id.nav_camara) {
fm.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
} else if (id == R.id.nav_gallery) {
fm.beginTransaction().replace(R.id.content_frame, new MusicFragment()).commit();
these both work fine with replacing each other although I have a big problem, when I select the nav drawer and hit the camera option it shows the fragment view but does not replace the content from activity_main it shows the fragment content on top of the content_main and doesn't replace it.
This is my MainActivity:
package com.justmikey.justmik;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v7.internal.widget.ButtonBarLayout;
import android.text.method.ScrollingMovementMethod;
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.Button;
import android.widget.TextView;
import JustMikey.Fragments.MainFragment;
import JustMikey.Fragments.MusicFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//create a media player object called mp
MediaPlayer mp;
//declare my buttons play, pause and stop
Button play, pause,stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the textView scrollMain to scrollable
TextView tv = (TextView) findViewById(R.id.scrollMain);
tv.setMovementMethod(new ScrollingMovementMethod());
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) {
android.app.FragmentManager fm = getFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camara) {
fm.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
} else if (id == R.id.nav_gallery) {
fm.beginTransaction().replace(R.id.content_frame, new MusicFragment()).commit();
} 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;
}
}
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior" tools:showIn="#layout/app_bar_main"
tools:context=".MainActivity"
android:background="#dbe4eb">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/content_frame">
<ImageView
android:layout_width="355dp"
android:layout_height="wrap_content"
android:src="#drawable/jmmain"
android:id="#+id/imageView2"
android:layout_gravity="center_horizontal|top"
android:layout_alignRight="#+id/content_frame"
android:layout_alignEnd="#+id/content_frame" />
<TextView
android:layout_width="fill_parent"
android:layout_height="274dp"
android:text="hello hello hello hello hello hello hello hello"
android:id="#+id/scrollMain"
android:layout_gravity="center_horizontal|bottom"
android:layout_alignBottom="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="28dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#ffffff"
android:padding="10dp"
/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center">
</ScrollView>
</FrameLayout>
</RelativeLayout>
FragmentTransactions only handle Fragments. They will not replace/remove anything not in a Fragment. Since those Views contained in the content_frame FrameLayout are only needed at startup, we can simply remove them upon the first FragmentTransaction.
To do this, we'll create a member boolean flag, isStartup, initialized to true. In the onNavigationItemSelected() method, we'll check the flag, and if it's true, remove the Views and change it to false.
Declare and initialize the boolean outside of any method:
private boolean isStartup = true;
Then do the check and removal in the onNavigationItemSelected() method.
public boolean onNavigationItemSelected(MenuItem item) {
android.app.FragmentManager fm = getFragmentManager();
int id = item.getItemId();
if(isStartup) {
((FrameLayout) findViewById(R.id.content_frame)).removeAllViews();
isStartup = false;
}
if (id == R.id.nav_camara) {
...
}
I had the same problem.
I could not solve my problem with the said solutions. But i found two solutions to solve it!
1- You can present the content of the main page into an other view group. and hide it in onNavigationItemSelected, in the right place:
content_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dbe4eb"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/my_linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView2"
android:layout_width="355dp"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/content_frame"
android:layout_alignRight="#+id/content_frame"
android:layout_gravity="center_horizontal|top"
android:src="#drawable/jmmain" />
<TextView
android:id="#+id/scrollMain"
android:layout_width="fill_parent"
android:layout_height="274dp"
android:layout_alignBottom="#+id/scrollView"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="28dp"
android:background="#ffffff"
android:padding="10dp"
android:text="hello hello hello hello hello hello hello hello" />
<ScrollView
android:id="#+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center"></ScrollView>
</LinearLayout>
</RelativeLayout>
onNavigationItemSelected method in MainActivity.java:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.main) {
findViewById(R.id.my_linearLayout).setVisibility(View.VISIBLE);
fragmentManager.popBackStack("fragment", POP_BACK_STACK_INCLUSIVE);
} else if (id == R.id.one) {
findViewById(R.id.my_linearLayout).setVisibility(View.GONE);
fragmentManager.beginTransaction().replace(R.id.content_frame, new OneFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.tow) {
findViewById(R.id.my_linearLayout).setVisibility(View.GONE);
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).addToBackStack("fragment").commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
2- The second way is to consider a fragment for the contents of the main page as well. and then in the onNavigationItemSelected method, we treat it Like the rest of the fragments:
onNavigationItemSelected method in MainActivity.java:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.main) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new HomeFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.one) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new OneFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.tow) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).addToBackStack("fragment").commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
note: To display the contents of the main page when opening the program enter the following code in onCreate() in MainActivity:
fragmentManager.beginTransaction().replace(R.id.content_frame, new HomeFragment()).addToBackStack("fragment").commit();

Android drag margin for navigation drawer is off screen

I have recently created an app called Hoops and I have been developing it for quite some time now. However, the main problem that I seem to be getting, is that the navigation drawer's swipe margin is off screen and other users find it incredibly hard to use the navigation drawer's swipe feature. The menu button works just fine though. I have looked at other tutorials online and all of them seem to be showing the same answer as the one in the forum I have linked: Set drag margin for Android Navigation Drawer
However, I have tried this solution, and it does not seem to be working for me. If anyone has any ideas why it is not working please can you help me out. Here is the coding for the Main activity with the navigation drawer below:
package com.jehan.sportstutorials;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBar actionBar;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
drawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
if (navigationView != null) {
setupNavigationDrawerContent(navigationView);
}
setupNavigationDrawerContent(navigationView);
}
#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) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupNavigationDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
textView = (TextView) findViewById(R.id.textView);
switch (menuItem.getItemId()) {
case R.id.item_navigation_drawer_basketball:
menuItem.setChecked(true);
textView.setText(menuItem.getTitle());
drawerLayout.closeDrawer(GravityCompat.START);
Intent i = new Intent(MainActivity.this, BasketballTutorial.class);
startActivity(i);
return true;
case R.id.item_navigation_drawer_help:
menuItem.setChecked(true);
textView.setText(menuItem.getTitle());
drawerLayout.closeDrawer(GravityCompat.START);
Intent intent2 = new Intent(MainActivity.this, HelpScreen.class);
startActivity(intent2);
return true;
}
return true;
}
});
}
}
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/navigation_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="#bool/fitsSystemWindows">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="#dimen/status_bar_kitkat_height"
android:background="?colorPrimary"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="?colorPrimaryDark"/>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/welcome"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textColor="#color/md_text"
android:singleLine="false"
android:padding="20dp"
android:gravity="center"
android:textStyle="bold"
android:textIsSelectable="false" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|bottom"
android:text="#string/swipe"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textColor="#color/md_text"
android:singleLine="false"
android:padding="20dp"
android:gravity="center"
android:textSize="20sp"
android:textStyle="italic"
android:layout_marginBottom="30dp"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="25dp"
android:background="?colorPrimaryDark"/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:minHeight="?attr/actionBarSize"
android:background="#drawable/action_bar_color"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ToolbarTheme"
android:layout_marginTop="25dp"/>
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="#bool/fitsSystemWindows"
app:headerLayout="#layout/navigation_drawer_header"
app:menu="#menu/navigation_drawer_menu"
app:theme="#style/NavigationViewTheme" />
If anyone wants a live example of the navigation drawers swipe feature not working you can test out my app in the app store. Here is the link: https://play.google.com/store/apps/details?id=com.jehan.sportstutorials
Summary: Does anyone know how to increase the navigation drawers drag margin, however not following the conventional methods stated in the link in my first paragraph? Help would be appreciated.
Check your R.layout.activity_main layout. Android Studio IDE, for some reason, sets 15dp margin to the topmost container of automatically-created Activity layouts. This could interfere with the Drawer.
Just check if the topmost Relative/Frame/Whichever Layout has any android:layout_marginX attributes set and remove them.

Hide support ActionBar while scrolling

I have an activity that has a support action bar, below that a sliding tab layout, below that a listview of images for the corresponding tab. I just want to hide the support action bar not the sliding tab strip and I am not able to hide it.
Here is my activity:
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
public class NewGalleriActivity extends AppCompatActivity implements ViewTreeObserver.OnScrollChangedListener {
Toolbar toolbar;
ViewPager viewPager;
NewGalleriPagerAdapter viewPagerAdapter;
SlidingTabLayout slidingTabLayout;
CharSequence Titles[] = {"Wildlife", "Architecture", "Black & White", "Close Up", "Night"};
int numOfTabs = 5;
private float mActionBarHeight;
private ActionBar mActionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_galleri);
final TypedArray styledAttributes = getTheme().obtainStyledAttributes(
new int[]{android.R.attr.actionBarSize});
mActionBarHeight = styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
//Initialise views
viewPager = (ViewPager) findViewById(R.id.pager);
slidingTabLayout = (SlidingTabLayout) findViewById(R.id.tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
mActionBar = getSupportActionBar();
int defaultValue = 0;
int page = getIntent().getIntExtra("ARG_PAGE", defaultValue);
viewPagerAdapter = new NewGalleriPagerAdapter(getSupportFragmentManager(), Titles, numOfTabs);
viewPager.setAdapter(viewPagerAdapter);
viewPager.setCurrentItem(page);
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return Color.parseColor("#FAC80A");
}
});
slidingTabLayout.setViewPager(viewPager);
if (android.os.Build.VERSION.SDK_INT >= 21)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(Color.parseColor("#263238"));
}
FloatingActionButton button = (FloatingActionButton) findViewById(R.id.ddd);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(NewGalleriActivity.this, ImageGridActivity.class);
startActivity(intent);
}
});
findViewById(R.id.parent).getViewTreeObserver().addOnScrollChangedListener(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_home, 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 onScrollChanged() {
float y = findViewById(R.id.parent).getScrollY();
if(y >= mActionBarHeight && mActionBar.isShowing()) {
mActionBar.hide();
} else if(y==0 && !mActionBar.isShowing()) {
mActionBar.show();
}
}
}
Here is my layout for the activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/black"
android:orientation="vertical">
<include layout="#layout/toolbar2" />
<com.pipipzz.simpleapp.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#231F20" />
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#drawable/drop_shadows" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/ddd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="24dp"
android:layout_marginBottom="10dp"
android:src="#drawable/fab_icons"
app:borderWidth="#null"
app:elevation="4dp"
app:fabSize="normal" />
</FrameLayout>
</ScrollView>
</LinearLayout>
Here is my layout for the toolbar:
<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/toolbar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFC80A"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<ImageView
android:id="#+id/tool_logo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="#string/tool_logo"
android:gravity="center_horizontal"
android:src="#drawable/logo_tool" />
</RelativeLayout>
<ImageView
android:id="#+id/tool_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="8dp"
android:contentDescription="#string/tool_search"
android:src="#drawable/search" />
</android.support.v7.widget.Toolbar>
Edit: Here is my layout for fragment that is shown in the tabs.
<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"
android:background="#231F20"
tools:context="com.pipipzz.simpleapp.ArchitectureFragment">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#null"
android:dividerHeight="0dp"
android:scrollingCache="true"
android:smoothScrollbar="true" />
</FrameLayout>
Any help would be highly appreciated.
Please have a look at this library Android-ObservableScrollView
It has a lot of examples and it will be much easier to use it in your case.
There are several examples of using it with Toolbar, that you are currently using in your code.
It would be better if you prodived all source code to run it, maybe you have issue somewhere else.
First about your code. Don't use findViewById whenever you want, it is really heavy method. So when you are doing this each time onScrollViewChanged it makes your app laggy.
Find your scroll view only once in onCreate method
mMainScrollView = findViewById(R.id.parent);
mMainScrollView.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {#Override
public void onScrollChanged() {
int scrollY = rootScrollView.getScrollY(); //for verticalScrollView
// Hide or show toolbar here
}
});
Why not directly to call hide on toolbar without getting support
action bar ? Try do to it directly on toolbar.
If you call hide
method directly on ActionBar/Toolbar does it work ?
Try to do something like this
To hide toolbar
toolbar.animate().translationY(-toolbar.getBottom()).setInterpolator(new AccelerateInterpolator()).start();
And show it again
toolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).start();

Categories

Resources