protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//identify object
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);
**title = (TextView)findViewById(R.id.theTitle);
Intent intent = getIntent();
String Title = intent.getExtras().getString("name");
title.setText(Title);**
}
#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(this, addCounter.class);
startActivity(intent);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
When nav_gallery = true, it brings me to activity2 which has the following code:
public void addOk(){
String sendName = name.getText().toString();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("name", sendName);
startActivity(intent);
}
I want to send the information from activity2 back to the main activity. Is my getIntent() in the wrong place?
Your getIntent() method is inside the onCreate method.
But onCreate is called only once, at creation. And if the MainActivity is still in the stack, there is no reason why onCreate() would be called again.
You should try to insert your code inside onResume() or onStart().
Related
This is the code. Please help me. If I click any item on NavigationView then the drawer was closing.
The app is running well but this one function is not working. When I debug this app then I saw navView.setNavigationItemSelectedListener is not called. If I click any item menu then close the drawer. How can I fix this issue? Please help me
private void initView() {
mToolbar = findViewById(R.id.dash_toolbar);
drawer = findViewById(R.id.drawer);
navView = findViewById(R.id.navigation_view);
bottomNavigationView = findViewById(R.id.bottom_navigation);
}
private void actionBar() {
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(R.string.app_name);
}
}
private void drawerMenu() {
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
AppBarConfiguration mAppBarConfiguration = new AppBarConfiguration.Builder
(R.id.nav_home, R.id.nav_share)
.setDrawerLayout(drawer)
.build();
navView.setNavigationItemSelectedListener
(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
int id = menuItem.getItemId();
if (id == R.id.nav_home) {
Toast.makeText(DashboardActivity.this, "Home ", Toast.LENGTH_SHORT).show();
}
if (id == R.id.nav_share) {
Toast.makeText(DashboardActivity.this, "Share message", Toast.LENGTH_SHORT).show();
}
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
I have created a project int activity_main and want to add a Navigation drawer to it.
I have gone into the java folder. Right click > new > Actvity > Navigation Drawer activity.
Note: I DON't have an action bar, to create the menu button(3 stacked lines)
Now I don't know how to actually open the navigation drawer over activity_main, without the app crashing.
Thanks.
I've tried doing an on click listener with a button which has
the drawer layout defined as dl (DrawerLayout dl = (DrawerLayout)findviewbyIOd(R.id.Drawer_layout))
and have done
dl.openDrawer(Gravity.LEFT);
have tried putting the code from the NavDrawer activity into the activity_main, but app won't start.
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
Switch OnOff;
EditText editText;
int NumberPicked;
int NumberPicked2;
private DrawerLayout dl;
private ActionBarDrawerToggle abdt;
Values[] troughvals = new Values[8];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BobbleSelector BS = new BobbleSelector();
final DrawerLayout dl = (DrawerLayout)findViewById(R.id.dl);
Button btnChange = (Button) findViewById(R.id.btnChange);
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
btnChange.setOnClickListener( new View.OnClickListener(){
public void onClick(View v){
dl.openDrawer(Gravity.LEFT);
}
});
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return abdt.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
public void handleSwitchClick(View view) {
Switch s = (Switch) view;
boolean isChecked = s.isChecked();
}
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked){
switch (compoundButton.getId()){
case R.id.OnOff:
break;
}
}
}
Note: have disabled fab, because it could not be found in my project.
I have created a custom Menu for the Navigation Drawer
public class BobbleSelector extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bobble_selector);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Button fab = findViewById(R.id.btnChange);
// 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 = findViewById(R.id.dl);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.dl);
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.bobble_selector, 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();
DrawerLayout drawer = findViewById(R.id.dl);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Drawer Layout
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/dl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_bobble_selector"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<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_bobble_selector"
app:menu="#menu/nav_menu" />
</android.support.v4.widget.DrawerLayout>
From Logcat
2019-06-02 13:13:08.195 12745-12745/com.example.mytest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mytest, PID: 12745
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.openDrawer(int)' on a null object reference
at com.example.mytest.MainActivity$1.onClick(MainActivity.java:49)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Expected to open drawer with the changebutton.openDrawer(Gravity.Left) But crashes the app.
Found I needed to move the code relating to the nav bar to the bottom of OnCreate and set the "SetContentView()" to be the layout for the Navigation bar.
Then it worked perfectly.
Before
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btnChange);
drawer = findViewById(R.id.dl);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer, R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//Not nav
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
//not nav
}
After
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btnChange);
//Not nav
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
//not nav
setContentView(R.layout.activity_bobble_selector);
drawer = findViewById(R.id.dl);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer, R.string.navigation_drawer_open,R.string.navigation_drawer_close);
assert drawer != null;
drawer.addDrawerListener(toggle);
toggle.syncState();
}
I am trying to make an app in which there will be a spinner with several values. A button will print that value in a text holder.
But, as you can see in the code bellow, the program cannot resolve the symbols "Teste1" and "Teste2".
Spinner merendas;
String[] morfes = {"Teste1","Teste2"};
ArrayAdapter <String> adapter;
merendas = (Spinner)findViewById(R.id.merendas);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,morfes);
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);
merendas.setAdapter(adapter);
merendas.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long morfes) {
switch (position){
case 0:
morfes = Teste1;
break;
case 1:
morfes = Teste2;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
Thanks for your time.
A button will print that value in a text holder.
If you want to print which spinner item is selected , You don't need setOnItemSelectedListener() for your spinner.
You can simply use
String selected = spinner.getSelectedItem().toString();
yourtextview.setText(selected);
I have two fragments MainFragment and First_Fragment. First fragment contains a video view but whenever I try to rotate, nav drawer always goes back to its main fragment. How could I save or restore my fragment state ? so it would stop going back to its main fragment.
Here's my code for the MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
VideoView videoView;
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainFragment first = new MainFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, first);
fragmentTransaction.commit();
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
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
MainFragment first = new MainFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, first);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
First_Fragment first = new First_Fragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, first);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
}
When you're not handling the activity change like orientation, keyboard, etc. it will automatically recreates the activity. Therefore you're fragment does not save your previous instance. To solve that, I only encounter two solution.
The first one is already mentioned by Zeeshan that handle your orientation change by following this step:
Handle the orientation change in your AndroidManifest
<activity
android:name="com.example.Activity"
android:label="Activity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="stateHidden|adjustResize"
android:theme="#style/Theme.AppCompat.Light" />
Handle the event in the onConfiguration Change method
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
The second one is to save the fragment state. Refer here https://stackoverflow.com/a/17135346/5870896
You can do setRetainInstance(true) in your fragments, but a BottomNavigationBar will work incorrectly. In this case you can use some boolean flag in activity and save/restore it with Bundle like this:
In onCreate:
if (savedInstanceState != null) {
isMapFragmentVisible = savedInstanceState.getBoolean("isMainVisible");
} else {
navigator.navigateToFragment(fragmentLocation);
}
In onSavedInstanceState:
outState.putBoolean("isMainVisible", isMapFragmentVisible);
In onNavigationSelectedListener:
case R.id.bottom_navigation_map:
if (isMapFragmentVisible) {
break;
} else {
navigator.navigateToFragment(fragmentMap);
isMapFragmentVisible = true;
}
return true;
case R.id.bottom_navigation_location:
if (!isMapFragmentVisible) {
break;
} else {
navigator.navigateToFragment(fragmentLocation);
isMapFragmentVisible = false;
}
return true;
For me it works perfect. Are there any more elegant ways?
Activity recreates when you rotate the device. you need to mention in your manifest that you will handle the orientation change in your code so that system don't do it like this:
<activity name="MainActivity" android:configChanges="keyboardHidden|orientation|screenSize"/>
and then handle the event
#Override
public void onConfigurationChanged(Configuration newConfig) {
}
in your activity
Write this in manifests.xml
android:configChanges="orientation"
like this:-
<activity
android:name=".fragmentLayouts.MainActivity"
android:configChanges="orientation" />
Add this to your java code:-
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
drawerListener.onConfigurationChanged(newConfig);
}
I am new to android and I am trying to learn by making a simple chat app in android studio.
I started by creating a navigation drawer. Now I want to add tabs to my app like this - chats / contact / calls below navigation drawer, but I could not find a simple step by step tutorial for doing this.
Before I started this chat app I worked on a simpler app and added some tabs to that old app like this:
public class MainActivity extends TabActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources resources = getResources();
TabHost tabHost = getTabHost();
// First tab
Intent intentTabOne = new Intent().setClass(this, TabOneActivity.class);
TabSpec tabSpecTabOne = tabHost
.newTabSpec("Tab One")
.setIndicator("", resources.getDrawable(R.drawable.icon_one_config))
.setContent(intentTabOne);
// Second tab
Intent intentTabTwo = new Intent().setClass(this, TabTwoActivity.class);
TabSpec tabSpecSecondTab = tabHost
.newTabSpec("Tab Two")
.setIndicator("", resources.getDrawable(R.drawable.icon_two_config))
.setContent(intentTabTwo);
// Third tab
Intent intentTabThree = new Intent().setClass(this, TabThree.class);
TabSpec tabSpecSent = tabHost
.newTabSpec("Tab Three")
.setIndicator("", resources.getDrawable(R.drawable.icon_three_invitations_config))
.setContent(intentTabThree);
// add all tabs
tabHost.addTab(tabSpecTabOne);
tabHost.addTab(tabSpecTabTwo);
tabHost.addTab(tabSpecTabThree);
//set Windows tab as default
tabHost.setCurrentTab(0);
}
But now my main activity looks like this:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
}
#Override
public void onBackPressed()...
Also, since TabActivity is now deprecated and I think I should use fragment, I got a little bit lost. I would really appreciate if someone could point me in the right direction. Thanks in advance.
I'd suggest to use a TabLayout that you can put below your Toolbar/Actionbar, so you can use it in parallel with the navigation drawer.
This answer shows how setup the Tabbar with a ViewPager. In short: You need to include the Design Support Library to use the TabLayout. In your XML layout, put the TabLayout and the ViewPager somewhere below the Toolbar, such that it fits your intentions. Then you can setup the different tabs with their own Fragments in your Activity.