I used the basic "Navigation Drawer Acticity" in Anroid Studio when creating the new project. The fragments work well and I've managed to add new fragments and everything.
However, items in the drawer menu that direct you to a certain website don't work. I've tried different methods with public boolean onNavigationItemSelected(MenuItem item){} and nothing happens when I press the items.
It looks like this:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_moodle) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
return true;
}
return true;
}
As you can see I did nothing for the fragments to work since they work fine already but when I press the button "moodle", nothing happens.
What have I done wrong?
Here is my MainActivity:
package com.example.ustudy;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.widget.Toast;
import com.example.ustudy.ui.home.HomeFragment;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.example.ustudy.databinding.ActivityMainBinding;
import org.jetbrains.annotations.NotNull;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private AppBarConfiguration mAppBarConfiguration;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//required for the top bar to be clickable
setSupportActionBar(binding.appBarMain.toolbar);
//button in the bottom right corner
binding.appBarMain.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 = binding.drawerLayout;
//Navigationview for the drawer (implemented in "activity_main.xml")
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
//each screen mentioned in the columns below (R.id.xy) will show the hamburger menu in the top left corner
//on screens, not included in the columns, there will be a "back arrow" instead of the ham. menu
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_nachricht, R.id.nav_lerngruppe, R.id.nav_lehrveranstaltung)
.setDrawerLayout(drawer)
.build();
//controls what happens when one of the items in the hamburger menu is clicked on
//go to "mobile_navigation.xml" to add screens to go to
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
//required to set up the hamburger menu icon and the back-arrow icon on the top bar(without it
//the user had to slide the side of the screen to open the menu)
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
//enables the items in the hamburger menu to go to a certain screen after clicking on them
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu (three dots on the right); this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
//enables the usage of the back-arrow on every screen
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(#NonNull #NotNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_moodle) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
return true;
}
return true;
}
}
Please, let me know if you need more!
Related
I am a new coder, creating a higher or lower guessing game app in Android Studio using the Java language. My goal for this project is for the user to be able to input a number between 1 and 100, and for the app to be able to pick a random number each time the user plays the game, and for the app to be able to tell the user if the number they picked is the correct answer, or higher or lower. I am using Android studio using Java. I have all the code there, I just keep getting a couple error answers. For instance, on my "if (guess < theNumber) statements, the word "guess is in red" and says it cannot resolve symbol guess. And the statement "private Button btnGuess" the btnGuess is in grey and it says that it's never used, but I have the id in the design tab of Android Studio and it's id is labeled btnGuess and I thought that I wired it into the code, when I try to run the app through the emulator it just does not even run. I've tried googling around for the answer, but since I am new to coding I'm not sure that I'm asking the correct questions, I've included the code for reference, thank you very much in advance.
ckage com.example.billyhodgesguessinggame;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.billyhodgesguessinggame.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText txtGuess;
private Button btnGuess;
private TextView lblOutput;
private int theNumber;
public void checkGuess() {
String guessText = txtGuess.getText().toString();
String message = "";
try {
int Guess = Integer.parseInt(guessText);
if (guess < theNumber)
message = guess + "is too low. Try again.";
else if (guess > theNumber)
message = guess + "is too high. Try again.";
else {
message = guess +
"is correct. You win! Let's play again!";
newGame();
}
} catch (Exception e) {
message = "Enter a whole number between 1 and 100.";
} finally {
lblOutput.setText(message);
txtGuess.requestFocus();
txtGuess.selectAll();
}
}
private AppBarConfiguration appBarConfiguration;
public void newGame() {
theNumber = (int)(Math.random() * 100 + 1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtGuess = findViewById(R.id.txtGuess);
Button btnGuess = findViewById(R.id.btnGuess);
lblOutput = findViewById (R.id.lblOutput);
newGame();
btnGuess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
checkGuess();
}
});
com.example.billyhodgesguessinggame.databinding.ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
binding.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();
}
});
}
#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);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
}
You use Guess and guess as variable names. Stick to the lowercase version and only use guess.
In this line, remove Button at the beginning. Otherwise, you declare a new variable instead of reusing the existing one which you already declared at the top.
Button btnGuess = findViewById(R.id.btnGuess);
I am currently making a program which opens a menu with a traditional menu button. There two different buttons: first should open the left side menu and the second is made for opening settings. The problem is both these buttons open the same menu. Please help me to make things so that each button opens its own menu.
I've made the main part of the app with a youtube video about these buttons. But there is a problem with them.
The following is the snapshot of menu that is opened with left side button:
And the following is the look of the app
And the following is the snapshot of the same menu opened with second button
Here is my code:
package com.danielliakhovetskyi.mainactivity;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MainActivity extends AppCompatActivity {
Menu menu;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
NavigationView navigationView;
MenuItem maths;
private boolean menuItemsAssigned = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Objects.requireNonNull(getSupportActionBar()).setBackgroundDrawable(new ColorDrawable
(Color.parseColor("#872be3"))); //making ActionBar light-coloured
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.abs_layout);
drawerLayout = findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = findViewById(R.id.navview);
navigationView.setItemTextAppearance(R.style.WithFont);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
Toast.makeText(MainActivity.this, "Default is clicked", Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
} else {
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.navigation_menu, menu);
/* this.menu = menu;
maths = menu.findItem(R.id.maths);
Logger.getGlobal().log(Level.INFO, "Maths Clicked");
Toast.makeText(this, "" + maths, Toast.LENGTH_SHORT).show();
maths.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
maths.setTitle("Maths");
Toast.makeText(MainActivity.this, "WORKS " + maths, Toast.LENGTH_SHORT).show();
Logger.getGlobal().log(Level.INFO, "Maths Clicked");
return false;
}
});
menuItemsAssigned = true;*/
return true;
}
}
In onCreateOptionsMenu() there is this line:
getMenuInflater().inflate(R.menu.navigation_menu, menu);
which apparently is wrong because it inflates the menu for the navigation drawer as the action bar menu.
Replace R.menu.navigation_menu with the menu for the action bar.
I am currently writing an app that includes a BottomNavigationBar (android studio)
but I got a problem:
I want the layouts to switch (or at least the TextViews inside each),
currently the navigation is not doing more than switching between single strings. so how can I make it work? please give me a step-by-step guide because I am fairly new to this whole stuff.
here's some code:
package com.john.doe.mycvasapp;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
public class Personal extends AppCompatActivity {
private TextView mTextMessage;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.personal:
mTextMessage.setText(R.string.personal1);
return true;
case R.id.school:
mTextMessage.setText(R.string.school1);
return true;
case R.id.work:
mTextMessage.setText(R.string.work1);
return true;
case R.id.skills:
mTextMessage.setText(R.string.skills1);
return true;
case R.id.lastly:
mTextMessage.setText(R.string.lastly1);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_persoenliche_daten);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
}
thanks for all the incoming help,
regards, guy from internet
I am creating a small app that will allow the user to view different categories of books for college.
So far in the activity main drawer I have a few different categories that should load a layout with a listView and populate this list from an arrayAdapter when selected. I have it set up and semi-working on one of my layouts, but the problem arises when I change to a different category from the navigation drawer, the listView is still displayed on the screen and I can't seem to figure out how to get it to stop.
I thought that I would need to use endTransaction() but I'm not really sure yet if I'm using the right thing.
I am a beginner to Java and Android Studio, so I hope that I am making sense in what I am asking.
If more code or information is needed, I will be happy to provide.
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.ViewGroup;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import java.util.ArrayList;
import java.util.List;
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);
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);
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
//loads the home screen when app launches
displaySelectedScreen(R.id.nav_home);
}
#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);
}
private void displaySelectedScreen(int id) {
Fragment fragment = null;
//loads each layout inflator depending on what menu item has been clicked
switch(id) {
case R.id.nav_home:
fragment = new Home();
break;
case R.id.nav_book:
fragment = new All();
break;
case R.id.nav_sci_fi:
fragment = new SciFi();
break;
case R.id.nav_fantasy:
fragment = new Fantasy();
break;
case R.id.nav_dystopian:
fragment = new Dystopian();
break;
case R.id.nav_about:
fragment = new About();
break;
case R.id.nav_contact:
fragment = new ContactUs();
break;
}
if(fragment != null) {
FragmentTransaction ft = getSupportFragmentManager(). beginTransaction();
ft.replace(R.id.content_main, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
FragmentManager fm=getSupportFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_book) {
// Handle the camera action
} else if (id == R.id.nav_sci_fi) {
fm .beginTransaction().replace(R.id.content_frame, new BookFragment()).commit(); setTitle("Sci-Fi");
//TODO: endTransaction
} else if (id == R.id.nav_fantasy) {
} else if (id == R.id.nav_dystopian) {
} else if (id == R.id.nav_about) {
}
displaySelectedScreen(id);
return true;
}
}
Your displaySelectedScreen() function is using a FragmentTransaction instead of FragmentManager. Try using FragmentManager.
I am trying to build a Translucent Navigation bar for my android app. I separately tried developing the task bar and then had intend to include it in my application.
I am not allowed to upload images yet (as I don't have the reputation), therefore here's an example of what I am trying to build for my APP:
Image Slider example
I am getting errors in the MainActivity.java file.
I get an Error in the following line of code :
mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.navigation_drawer_open, R.string.navigation_drawer_close)
Error :
Error:(48, 79) error: cannot find symbol variable navigation_drawer_open
Error:(48, 112) error: cannot find symbol variable navigation_drawer_close
This is the entire code of MainActivity.java file:
package sha.testing_sidebar;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends ActionBarActivity {
String TITLES [] = {"Home","Events","Mail","Blog","Attending"};
int ICONS [] = {R.drawable.ic_home,R.drawable.ericsson_2_png,R.drawable.ic_mqil_hdpi,R.drawable.ic_blog_2,R.drawable.ic_attending};
String NAME = "Sharang Bharadwaj";
String EMAIL = "sha.bh91#gmail.com";
int PROFILE = R.drawable.sha1;
private Toolbar toolbar;
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
DrawerLayout Drawer;
ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
mRecyclerView.setHasFixedSize(true);
mAdapter = new sha.testing_sidebar.MyAdapter(TITLES,ICONS,NAME,EMAIL,PROFILE);
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(this);
Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
//actions upon opening slider
//presently nothing
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
//actions upon closing slider
//presently nothing
}
};
//Drawer Toggle Object made
Drawer.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#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);
}
}
The error is
Add the following in your strings.xml file
<string name="navigation_drawer_open">Drawer Open</string>
<string name="navigation_drawer_close">Drawer Closed</string>
It should work after that.
Just copy/paste this in the strings file
<string name="navigation_drawer_open">Drawer Open</string>
<string name="navigation_drawer_close">Drawer Closed</string>
they might be there already, if true, both will be underlined in red.
if so erase the existing ones and copy/paste the same two lines.