How to open Fragment from NavigationDrawer that uses onNagivationItemSelected - java

My MainActivity uses onNavigationItemSelected(MenuItem item) that includes an activity. But somehow it won't open the other fragments that I have on the drawer. I can open the fragments if i delete navigationView.setNavigationItemSelectedListener(this). But then I can't open BookingActivity.
My MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
//region Properties
private AppBarConfiguration mAppBarConfiguration;
ImageButton settings_btn;
//endregion
#Override
protected void onStart() {
super.onStart();
ProductDatabase productDb = new ProductDatabase();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
settings_btn = findViewById(R.id.btn_settings);
settings_btn.setOnClickListener(v ->
startActivity(new Intent(MainActivity.this, SettingsActivity.class)));
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show());
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_login, R.id.nav_treatments, R.id.nav_product, R.id.nav_about, R.id.nav_contactUs)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
navigationView.setNavigationItemSelectedListener(this); // Fragments work if I remove this line, but not BookingActivity
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_booking) {
startActivity(new Intent(this, BookingActivity.class));
} else if (id == R.id.nav_home) {
} else if (id == R.id.nav_product) {
// What to write here to open ProductFragment?
} else if (id == R.id.nav_treatments) {
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_contactUs) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

please try this link How to go to fragment from activity
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_booking) {
startActivity(new Intent(this, BookingActivity.class));
} else if (id == R.id.nav_home) {
} else if (id == R.id.nav_product) {
// here you will set intent
} else if (id == R.id.nav_treatments) {
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_contactUs) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

Related

ID does not reference a View inside this Activity

I keep getting an IllegalArgumentException in my MainActivity code, please help me! The error is being shown on the line
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
I am trying to add in the QR code reader into the Main Activity, but when I did so, this error popped up
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private SharedPreferences appData;
private Button scan_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_scan);
scan_button = (Button) findViewById(R.id.btnScan);
final Activity activity = this;
scan_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*FloatingActionButton fab = 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 = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_transaction, R.id.nav_qrcode,
R.id.nav_login, R.id.nav_logout, R.id.nav_signup, R.id.nav_rewards, R.id.nav_scan)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
appData = getSharedPreferences("appData", this.MODE_PRIVATE);
SharedPreferences.Editor editor = appData.edit();
editor.putFloat("Point", 0);
//editor.putBoolean("SAVE_LOGIN_DATA", checkBox.isChecked());
editor.putString("ID", "");
editor.putString("PWD", "");
editor.apply();
//Navigation.findNavController(navigationView).navigate(R.id.nav_login);
}
#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 onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public boolean onChangeMenuItem() {
NavigationView navigationView = findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
MenuItem nav_dashboard = menu.findItem(R.id.nav_login);
nav_dashboard.setVisible(false);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "You Cancelled the Scan", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
String scanResult = data.getStringExtra("SCAN_RESULT");
int pointsAdded = Integer.parseInt(scanResult);
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}

Navigation Icon causes application to close

I am a newbie to Android Studio but have successfully gone quite far, including a successful login screen. But I am getting stuck at a point.
The navigation icon created using ActionBarDrawerToggle works fine on the homescreen. Then on clicking on any of the options, it successfully loads the fragment. But when I click on the the icon again to go to another fragment, the navigation drawer open but the application closes. The debugger shows no error, it only reports that the onStop and onPause events have been triggered (which are empty since I have no use with them).
I have tried a lot but I am unable to find a solution to this problem.
I even attempted to create a custom view on the ActionBar with a custom ImageButton, and I set a click listener. That worked fine, but I want to use the default method, i.e. ActionBarDrawerToggle.
Open to all suggestions!
My HomeAcivity.java, where I am using the alternate I custom-built.
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
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();
}
});
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.actionbar, null);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(v);
ImageButton drawer = (ImageButton) findViewById(R.id.btn1);
drawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
});
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.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_logout) {
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
SessionManager session = new SessionManager(getApplicationContext());
db.deleteUsers();
session.setLogin(false);
Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
startActivity(intent);
finish();
return true;
}else if(id == android.R.id.home){
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
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_profile) {
ProfileFragment profileFragment = new ProfileFragment();
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_home_fragment, profileFragment, profileFragment.getTag()).commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.profile_heading);
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_cmi) {
} else if (id == R.id.nav_inspire) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

ask runtime permissions for onMapsReady android

i have a phone with android 6.0, and the method onMapReady is not execute, because i think need runtime permissions, and i dont know how to do that, this is my code
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback {
GoogleMap map;
GoogleApiClient mGoogleApiClient;
String email;
#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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
//obtener datos para la barra
if(user != null) {
String nombre=user.getDisplayName();
email=user.getEmail();
Uri foto=user.getPhotoUrl();
NavigationView navigationsView = (NavigationView) findViewById(R.id.nav_view);
View hView = navigationsView.getHeaderView(0);
TextView nav_user = (TextView)hView.findViewById(R.id.txtMail);
TextView name=(TextView) hView.findViewById(R.id.txtNombre);
ImageView img_user = (ImageView)hView.findViewById(R.id.profile_image);
name.setText(nombre);
nav_user.setText(email);
Picasso.with(this).load(foto).into(img_user);
}
else {
SharedPreferences loginbdd=getSharedPreferences("login", Context.MODE_PRIVATE);
email=loginbdd.getString("nombre","");
String nombre=loginbdd.getString("mail","");
NavigationView navigationsView = (NavigationView) findViewById(R.id.nav_view);
View hView = navigationsView.getHeaderView(0);
TextView nav_user = (TextView)hView.findViewById(R.id.txtMail);
TextView name=(TextView) hView.findViewById(R.id.txtNombre);
ImageView img_user = (ImageView)hView.findViewById(R.id.profile_image);
nav_user.setText(email);
name.setText(nombre);
}
}
private void goLogin() {
Intent intent = new Intent(this, Login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
new AlertDialog.Builder(MainActivity.this)
.setIcon(R.drawable.cerrar).setTitle("Cerrar Aplicación").setMessage("Deseas cerrar CicloMapp?")
.setCancelable(true).setPositiveButton("Si", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
})
.setNegativeButton("No", null).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.endSession) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(R.drawable.cerrar)
.setTitle("Cerrar sessión")
.setMessage("Deseas cerrar sesión?")
.setCancelable(true)
.setPositiveButton("Si", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
if(user!= null){
LoginManager.getInstance().logOut();
FirebaseAuth.getInstance().signOut();
goLogin();
}else{
SharedPreferences loginbdd=getSharedPreferences("login", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=loginbdd.edit();
editor.remove("inicio");
editor.commit();
goLogin();
}
}
})
.setNegativeButton("No", null).show();
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.AgregarRuta) {
} else if (id == R.id.ValorarRuta) {
Intent i = new Intent(MainActivity.this, Valoraraciones.class);
i.putExtra("correo", email);
startActivity(i);
} else if (id == R.id.ReportarRuta) {
Intent i = new Intent(MainActivity.this, Reportar.class);
i.putExtra("correos", email);
startActivity(i);
} else if (id == R.id.Eventos) {
} else if (id == R.id.Refresco) {
} else if (id == R.id.Leyes) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onMapReady(final GoogleMap googleMap) {
map=googleMap;
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
map.getUiSettings().setMapToolbarEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(true);
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(-33.447487,-70.673676));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(11);
map.moveCamera(center);
map.animateCamera(zoom);
Polyline po = new Polyline();
po.AddPolyline(map);
int height = 50;
int width = 50;
BitmapDrawable bitmapdraw = (BitmapDrawable) getResources().getDrawable(R.drawable.mruta);
Bitmap b = bitmapdraw.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
final Marcadores ma=new Marcadores();
ma.MarcadoreBdd(map,smallMarker);
}
}
maybe the onmylocation needs permissions ithink
ps: works perfect with android 4.4, the problem is with android 6.0 or higher
I also struggled with the runtime permissions when upgrading my app to a new Android version.
But I found this post very helpful:
https://inducesmile.com/android/android-6-marshmallow-runtime-permissions-request-example/
(The code below comes from this).
Basically, you need to check if you have the permissions in your App when you need them (perhaps during startup in your case) with code such as this;
if (ContextCompat.checkSelfPermission(WebActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
}
Then, you need to handle a response in an onRequestPermissionsResult method
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == MY_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//You have permission, so continue
}else if (grantResults[0] == PackageManager.PERMISSION_DENIED){
if (ActivityCompat.shouldShowRequestPermissionRationale(WebActivity.this, Manifest.permission.RECORD_AUDIO)) {
//Show an explanation to the user *asynchronously*
ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
}else{
//Never ask again and handle your app without permission.
}
}
}
}
Don't forget that you still need the permissions to be specified in your MANIFEST file.

Navigation drawer: how to make the item direct you to a website. Android Studio

Hi guys perfect saturday for some coding :)
I have a navigation drawer where i can click on items and they direct me to fragments. But how i make so when i press an item in the navigation drawer to link me to a website. I'm not really good at items..
I will post three different imgur images See the 3 images here
So when you press it, example: www.google.com comes up in your regular "chrome app" i'm not really interested in webview cause of the website is not html5.
This is my MainActivity at the bottom of it you can find how i use the items for my fragments.
I'm a rookie programmer hehe... But it is so fun! Learning step by step.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//TextView tstnr;
TextView radertst;
Button sendSMSaon;
EditText aonTxt;
//TextView nrladd;
#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);
// tstnr = (TextView) findViewById(R.id.nummertestsp);
radertst = (TextView) findViewById(R.id.raderanumtxt);
sendSMSaon = (Button)findViewById(R.id.skickaaon);
aonTxt = (EditText)findViewById(R.id.aon);
// nrladd = (TextView)findViewById(R.id.numretladd);
}
//This is where the call for the value in the setttings are.
//Här är så att man kan lägga in values från inställningar till mainactivity.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");
}
//downbelow is where the onresume so the value boots up with the app.
//nedanför är för att appen ska ladda koden i settings direkt när man startar
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");}
#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) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You need something like this in your onClick method of a button, or listener, however you wanna handle the click event:
Intent intent = new Intent("android.intent.action.VIEW",
Uri.parse("http://www.google.com/"));
startActivity(intent);
If you don't know how to handle the click itself check this out., but I see in your code that you can, so it's fine.
Just add this on your menu item
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
so on your onNavigationItemSelected you have to add another if and search for the id of the item you need:
I made an example
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
else if (id == R.id.YOUR_ITEM_ID) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
return true;
}
return true;
}

want to use setvisibily method betwen two framelayout in android

I am trying to use two framelayouts to load the content. My problem is both pages are showing data at the same time. I want to use setVisibilty method in the main java file. When one frame is showing data the other frame hides automatically. Could anyone tell me the java codes. Here is the xml file:
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<FrameLayout
android:id="#+id/content_frametwo"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
I am giving you the java file here:-
#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);
}
private void setFrameVisibility(boolean frameOneVisible){
if (frameOneVisible){
findViewById(R.id.content_frame).setVisibility(View.VISIBLE);
findViewById(R.id.content_frametwo).setVisibility(View.GONE);
} else {
findViewById(R.id.content_frame).setVisibility(View.GONE);
findViewById(R.id.content_frametwo).setVisibility(View.VISIBLE);
}
}
#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();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.homepage) {
Intent homepage = new Intent (MainActivity.this, MainActivity.class);
startActivity(homepage);
// Handle the camera action
} else if (id == R.id.foodpage) {
//handle the food page here
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
} else if (id == R.id.schedulepage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ScheduleFragment())
.commit();
} else if (id == R.id.emotionspage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new EmotionsFragment())
.commit();
} else if (id == R.id.basicneedspage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frametwo
, new BasicneedsFragment())
.commit();
} else if (id == R.id.exit) {
askBeforeExit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void onBackPressed() {
askBeforeExit();
}
private void askBeforeExit(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Confirm Exit");
builder.setMessage("Are you sure you want to quit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert=builder.create();
alert.show();
}
}
You could make a function to set them both, but then you will have to make sure you always use that function:
private void setFrameVisibility(boolean frameOneVisible) {
if (frameOneVisible) {
findViewById(R.id.content_frame).setVisibility(View.VISIBLE);
findViewById(R.id.content_frametwo).setVisibility(View.GONE);
} else {
findViewById(R.id.content_frame).setVisibility(View.GONE);
findViewById(R.id.content_frametwo).setVisibility(View.VISIBLE);
}
}
You can implement this by using this code:
inside onCreateView:
frameLayout1 = (FrameLayout) findViewById(R.id.frameLayout1);
frameLayout2 = (FrameLayout) findViewById(R.id.frameLayout2);
When ever you want to change visibility:
frameLayout1.setVisibility(View.VISIBLE);
frameLayout2.setVisibility(View.GONE);

Categories

Resources