I've been searching through Stack Overflow but couldn't seem to find something useful about this issue I am having ..
Below I have attached the code for the Home Activity that I have, and the XML file for it. I cant seem to get my head around what the problem is, I dunno what I am doing wrong. I want to show the content of a third class (e.g. the a different Fragment class for each of my fragments, basically I want to be able to show all the of the fragments in the same fragment holder in the home activity.. in this case I am trying to open the fragment Bookmarks (men.bookmarks)..
Any suggestions guys?
I didn't include the code for the fragment as it would be a lot of classes then, but If you need it, tell me :) ..
XML file for my HomeActivity:
<?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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start" >
<include
layout="#layout/app_bar_home"
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_home"
app:menu="#menu/activity_home_drawer" />
<fragment
android:name="com.nooriandroid.n007.mybookmarks_v1.Fragment_Bookmarks"
android:id="#+id/fragBookmarks"
android:layout_weight="2"
android:layout_width="25dp"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
package com.nooriandroid.n007.mybookmarks_v1;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
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.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Activity_Home extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
//--------------Variables---------------------//
private String date_pattern = "hh:mm dd-MM-yyyy";
private Fragment fragment_bookmarks;
private Fragment_Favorite fragment_favorite;
private Fragment_Category fragment_category;
private Fragment_SharedWith_me fragment_sharedWith_me;
private Fragment_Myshared fragment_myshared;
private Activity_Home homeActivity;
private Fragment_Item_Container fragment_item_container;
private User user;
private boolean frag_favorite_visible = false, frag_bookmark_visible = false, frag_category_visible = false,
frag_myshared_visible = false, frag_sharedwithme__visible = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
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);
//---------------Customized------------------//
setTitle("Home");
ActionBar ab = getSupportActionBar();
ab.setLogo(R.mipmap.ic_logolight);
ab.setDisplayUseLogoEnabled(true);
ab.setDisplayShowHomeEnabled(true);
fragment_favorite = new Fragment_Favorite();
fragment_bookmarks = new Fragment_Bookmarks();
fragment_category = new Fragment_Category();
fragment_myshared = new Fragment_Myshared();
fragment_sharedWith_me = new Fragment_SharedWith_me();
fragment_item_container = new Fragment_Item_Container();
homeActivity = this;
FragmentManager fragmentManager = getFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment_favorite);
fragmentTransaction.add(R.id.fragment_container, fragment_bookmarks);
fragmentTransaction.add(R.id.fragment_container, fragment_category);
fragmentTransaction.add(R.id.fragment_container, fragment_myshared);
fragmentTransaction.add(R.id.fragment_container, fragment_sharedWith_me);
frag_favorite_visible = true;
fragmentTransaction.hide(fragment_bookmarks);
fragmentTransaction.hide(fragment_category);
fragmentTransaction.hide(fragment_myshared);
fragmentTransaction.hide(fragment_sharedWith_me);
fragmentTransaction.commit();
goHomeOnclicked();
user = new User();
user = (User) getIntent().getSerializableExtra("currentuser");
}
#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);
rundUserSettings();
SimpleDateFormat format = new SimpleDateFormat(date_pattern);
String current_date = format.format(new Date());
TextView nav_textview_Date = (TextView) findViewById(R.id.textView_Date);
nav_textview_Date.setText(current_date);
TextView nameLast_textView = (TextView) findViewById(R.id.textView_UsernameLastname);
nameLast_textView.setText("" + user.getName() + " " + user.getLast_name());
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.men_newItem) {
Intent intent_NewItem = new Intent("com.nooriandroid.n007.mybookmarks_v1.Activity_NewItem");
startActivity(intent_NewItem);
} else if (id == R.id.men_bookmarks) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
fragmentTransaction.show(fragment_bookmarks);
frag_bookmark_visible = true;
this.setTitle("Bookmarks"); ///Ombytnings Zirt
fragmentTransaction.commit(); ///
} else if (id == R.id.men_category) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_category_visible= true;
fragmentTransaction.show(fragment_category);
fragmentTransaction.commit();
this.setTitle("Categories ");
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
}
else if (id == R.id.men_share) {
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
} else if (id == R.id.men_sharedwithme) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_sharedwithme__visible = true;
fragmentTransaction.show(fragment_sharedWith_me);
fragmentTransaction.commit();
this.setTitle("Shared with me");
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
} else if (id == R.id.men_myshared) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_myshared_visible = true;
fragmentTransaction.show(fragment_myshared);
fragmentTransaction.commit();
this.setTitle("My shared");
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void checkFragmentsStatus(FragmentTransaction fragmentTransaction){
if (frag_favorite_visible){
frag_favorite_visible = false;
fragmentTransaction.hide(fragment_favorite);
}else if (frag_bookmark_visible){
frag_bookmark_visible = false;
fragmentTransaction.hide(fragment_bookmarks);
}else if (frag_category_visible){
frag_category_visible = false;
fragmentTransaction.hide(fragment_category);
}else if (frag_myshared_visible){
frag_myshared_visible = false;
fragmentTransaction.hide(fragment_myshared);
}else if (frag_sharedwithme__visible){
frag_sharedwithme__visible = false;
fragmentTransaction.hide(fragment_sharedWith_me);
}
}
private void goHomeOnclicked(){
findViewById(R.id.toolbar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!frag_favorite_visible){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_favorite_visible = true;
fragmentTransaction.show(fragment_favorite);
fragmentTransaction.commit();
homeActivity.setTitle("Home");
}
}
});
}
private boolean rundUserSettings(){
if (this.user!=null){
try {
File file = new File(user.getProfile_pic());
Uri uri = Uri.fromFile(file);
ImageView view = (ImageView) findViewById(R.id.imageView_ProfilePic);
view.setImageURI(uri);
}catch (Exception e){
Toast.makeText(Activity_Home.this,"Unable to load profile picture.!",Toast.LENGTH_SHORT).show();
}
return true;
} else {
return false;
}
}
}
The code you're using for adding different fragments on the same activity is really messed up. You can use better approach. I'm adding the sample code below:
In the layout of Activity, add this line of code
<FrameLayout
android:id="#+id/fragBookmarks"
android:layout_weight="2"
android:layout_width="25dp"
android:layout_height="match_parent" />
instead of:
<fragment
android:name="com.nooriandroid.n007.mybookmarks_v1.Fragment_Bookmarks"
android:id="#+id/fragBookmarks"
android:layout_weight="2"
android:layout_width="25dp"
android:layout_height="match_parent" />
Now write this method in your HomeActivity to add different fragments
public void addFragment(Fragment frag, String tag) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragBookmarks, frag, tag);
transaction.addToBackStack(getFragmentManager().getBackStackEntryCount() == 0 ? "FirstFragment" : null).commit();
}
}
This method will help you to add any fragment to this activity on the go. You don't need to add all the fragments from the beginning. Like If now I'm on HomeFragment and I want to open BookmarkFragment on button click from Home, I will write something like;
btnBookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity) getActivity()).addFragment(new BookmarkFragment(), BookmarkFragment.class.getSimpleName()); // This will add the new fragment Bookmark fragment to the activity while adding it to backstack
}
});
Now, If you want to go back from BookmarkFragment to HomeFragment, add this method in your HomeActivity
public void popFragment() {
if (getFragmentManager() == null)
return;
getFragmentManager().popBackStack();
}
And Call this function in BookmarkFragment like,
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity) getActivity()).popFragment(); // This will remove the last added fragment Bookmark fragment
}
});
DrawerLayout should have only two direct children.If you want to replace different fragments in same activity,create a FrameLayout in the app_bar_home layout.Then in your Activity,do this to replace fragments.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frame_layout_id,new yourFragment()).commit();
Related
I'm using JUSTIFICATION_MODE_INTER_WORD. My application is running in the emulator. But when I test my tablet and phone, my application crashes.
This is because the JUSTIFICATION_MODE_INTER_WORD property works on API level 26.
But I want it to work in android 4.4.2.
Is this possible ?
Does the JUSTIFICATION_MODE_INTER_WORD feature work in android 4.4.2?
Any suggestions?
i tried this method but i couldn't
https://github.com/mathew-kurian/TextJustify-Android
Run Error
`E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.medicalsix.doctorsix, PID: 11989
java.lang.NoSuchMethodError: No virtual method setJustificationMode(I)V in class Landroid/widget/TextView; or its super classes (declaration of 'android.widget.TextView' appears in /system/framework/framework.jar:classes2.dex)
at com.medicalsix.doctorsix.MainActivity.onCreate(MainActivity.java:64)
at android.app.Activity.performCreate(Activity.java:6374)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2746)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2867)
at android.app.ActivityThread.access$900(ActivityThread.java:181)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1476)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6134)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
I/Process: Sending signal. PID: 11989 SIG: 9
Application terminated.`
Main Avtivity
package com.medicalsix.doctorsix;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.os.Environment;
import android.text.Layout;
import android.text.Spannable;
import android.view.MenuInflater;
import android.view.View;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import com.google.android.material.navigation.NavigationView;
import com.squareup.picasso.Picasso;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.Menu;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
TextView textview,text;
ImageView imageview;
WebView webview;
Button buttson;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setJustificationMode(Layout.JUSTIFICATION_MODE_INTER_WORD);
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);
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);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
hideItem();
TwoFalse();
ThreeFalse();
FourFalse();
}
private void hideItem()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.itemone).setVisible(false);
nav_Menu.findItem(R.id.itemtwo).setVisible(false);
nav_Menu.findItem(R.id.itemthree).setVisible(false);
nav_Menu.findItem(R.id.itemfour).setVisible(false);
nav_Menu.findItem(R.id.itemfive).setVisible(false);
nav_Menu.findItem(R.id.itemsix).setVisible(false);
nav_Menu.findItem(R.id.itemclose).setVisible(false);
}
private void hideItemvisible()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.itemone).setVisible(true);
nav_Menu.findItem(R.id.itemtwo).setVisible(true);
nav_Menu.findItem(R.id.itemthree).setVisible(true);
nav_Menu.findItem(R.id.itemfour).setVisible(true);
nav_Menu.findItem(R.id.itemfive).setVisible(true);
nav_Menu.findItem(R.id.itemsix).setVisible(true);
nav_Menu.findItem(R.id.itemclose).setVisible(true);
}
/* private void hidecloseitem()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.itemclose).setVisible(true);
}
private void hidecloseitemfalse()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.itemclose).setVisible(false);
}
private void twocloseTrue()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.twoclose).setVisible(true);
}
private void twocloseFalse()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.twoclose).setVisible(false);
}*/
private void TwoFalse()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.twoclose).setVisible(false);
nav_Menu.findItem(R.id.twotwo).setVisible(false);
nav_Menu.findItem(R.id.twothree).setVisible(false);
nav_Menu.findItem(R.id.twofour).setVisible(false);
nav_Menu.findItem(R.id.twofive).setVisible(false);
nav_Menu.findItem(R.id.twosix).setVisible(false);
nav_Menu.findItem(R.id.twoseven).setVisible(false);
nav_Menu.findItem(R.id.twoeight).setVisible(false);
nav_Menu.findItem(R.id.twonine).setVisible(false);
nav_Menu.findItem(R.id.twoteen).setVisible(false);
nav_Menu.findItem(R.id.twoeleven).setVisible(false);
nav_Menu.findItem(R.id.twotvelve).setVisible(false);
nav_Menu.findItem(R.id.twothirteen).setVisible(false);
nav_Menu.findItem(R.id.twofourteen).setVisible(false);
nav_Menu.findItem(R.id.twosixteen).setVisible(false);
nav_Menu.findItem(R.id.twoseventeen).setVisible(false);
nav_Menu.findItem(R.id.twoeigteen).setVisible(false);
nav_Menu.findItem(R.id.twonineteen).setVisible(false);
nav_Menu.findItem(R.id.twotwenty).setVisible(false);
nav_Menu.findItem(R.id.twotwentyone).setVisible(false);
nav_Menu.findItem(R.id.twotwentytwo).setVisible(false);
nav_Menu.findItem(R.id.twotwentythree).setVisible(false);
nav_Menu.findItem(R.id.twotwentyfour).setVisible(false);
nav_Menu.findItem(R.id.twotwentyfive).setVisible(false);
nav_Menu.findItem(R.id.twotwentysix).setVisible(false);
nav_Menu.findItem(R.id.twotwentyseven).setVisible(false);
}
private void TwoTrue()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.twoclose).setVisible(true);
nav_Menu.findItem(R.id.twoone).setVisible(true);
nav_Menu.findItem(R.id.twotwo).setVisible(true);
nav_Menu.findItem(R.id.twothree).setVisible(true);
nav_Menu.findItem(R.id.twofour).setVisible(true);
nav_Menu.findItem(R.id.twofive).setVisible(true);
nav_Menu.findItem(R.id.twosix).setVisible(true);
nav_Menu.findItem(R.id.twoseven).setVisible(true);
nav_Menu.findItem(R.id.twoeight).setVisible(true);
nav_Menu.findItem(R.id.twonine).setVisible(true);
nav_Menu.findItem(R.id.twoteen).setVisible(true);
nav_Menu.findItem(R.id.twoeleven).setVisible(true);
nav_Menu.findItem(R.id.twotvelve).setVisible(true);
nav_Menu.findItem(R.id.twothirteen).setVisible(true);
nav_Menu.findItem(R.id.twofourteen).setVisible(true);
nav_Menu.findItem(R.id.twosixteen).setVisible(true);
nav_Menu.findItem(R.id.twoseventeen).setVisible(true);
nav_Menu.findItem(R.id.twoeigteen).setVisible(true);
nav_Menu.findItem(R.id.twonineteen).setVisible(true);
nav_Menu.findItem(R.id.twotwenty).setVisible(true);
nav_Menu.findItem(R.id.twotwentyone).setVisible(true);
nav_Menu.findItem(R.id.twotwentytwo).setVisible(true);
nav_Menu.findItem(R.id.twotwentythree).setVisible(true);
nav_Menu.findItem(R.id.twotwentyfour).setVisible(true);
nav_Menu.findItem(R.id.twotwentyfive).setVisible(true);
nav_Menu.findItem(R.id.twotwentysix).setVisible(true);
nav_Menu.findItem(R.id.twotwentyseven).setVisible(true);
}
private void ThreeFalse()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.threeclose).setVisible(false);
}
private void ThreeTrue()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.threeclose).setVisible(true);
nav_Menu.findItem(R.id.threeone).setVisible(true);
}
private void FourFalse()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.fourclose).setVisible(false);
}
private void FourTrue()
{
NavigationView navigationView = findViewById(R.id.nav_view);
Menu nav_Menu = navigationView.getMenu();
nav_Menu.findItem(R.id.fourclose).setVisible(true);
nav_Menu.findItem(R.id.fourone).setVisible(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
#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 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.action_settings) {
hideItemvisible();
//hidecloseitem();
/*setTitle("First Fragment");
First first = new First();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,first).commit();
*/
}else if (id == R.id.itemclose) {
hideItem();
// hidecloseitemfalse();
}else if (id == R.id.itemone) {
setTitle("One Fragment deneme ");
One one = new One();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,one).commit();
}else if (id == R.id.itemtwo) {
setTitle("Two Fragment");
Two two = new Two();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,two).commit();
}else if (id == R.id.itemthree) {
setTitle("Three Fragment");
Three three = new Three();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,three).commit();
}else if (id == R.id.itemfour) {
setTitle("Four Fragment");
Four four = new Four();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,four).commit();
}else if (id == R.id.itemfive) {
setTitle("Five Fragment");
Five five = new Five();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,five).commit();
}else if (id == R.id.itemsix) {
setTitle("Six Fragment");
Six six = new Six();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,six).commit();
}else if (id == R.id.twoclose) {
TwoFalse();
}else if (id == R.id.twoone) {
TwoTrue();
}
else if (id == R.id.threeclose) {
ThreeFalse();
}else if (id == R.id.threeone) {
ThreeTrue();
}
else if (id == R.id.fourclose) {
FourFalse();
}else if (id == R.id.fourone) {
FourTrue();
}else if (id == R.id.twotwo) {
setTitle("İzofluran");
Seven seven = new Seven();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,seven).commit();
}
else if (id == R.id.twothree) {
setTitle("Porfiria");
Eight eight = new Eight();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,eight).commit();
}
else if (id == R.id.twofour) {
setTitle("Amanita Phalloides");
Nine nine = new Nine();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,nine).commit();
}
else if (id == R.id.twofive) {
setTitle("Civa Zehirlenmesi");
Teen teen = new Teen();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,teen).commit();
}
else if (id == R.id.twosix) {
setTitle("Aldrete Skorlaması");
Eleven eleven = new Eleven();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,eleven).commit();
}
else if (id == R.id.twoseven) {
setTitle("Baker Simionescu");
Twelve twelve = new Twelve();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,twelve).commit();
}
else if (id == R.id.twoeight) {
setTitle("TLR4-Sıcak Çarpması");
Thirteen thirteen = new Thirteen();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,thirteen).commit();
}
else if (id == R.id.twonine) {
setTitle("Süksinilkolin");
Fourteen fourteen = new Fourteen();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,fourteen).commit();
}
else if (id == R.id.twoteen) {
setTitle("Tubokürarin");
Sixteen sixteen = new Sixteen();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,sixteen).commit();
}
else if (id == R.id.twoeleven) {
setTitle("Remifentanil");
Seventeen seventeen = new Seventeen();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,seventeen).commit();
}
else if (id == R.id.twotvelve) {
setTitle("Santral Sinir");
Eigteen eigteen = new Eigteen();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,eigteen).commit();
}
else if (id == R.id.twothirteen) {
setTitle("Nondepolarizan Bloğu");
Nineteen nineteen = new Nineteen();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,nineteen).commit();
}
else if (id == R.id.twofourteen) {
setTitle("Depolarizan Bloğu");
Twenty twenty = new Twenty();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,twenty).commit();
}
else if (id == R.id.twosixteen) {
setTitle("Etomidat");
Twentyone twentyone = new Twentyone();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,twentyone).commit();
}
else if (id == R.id.twoseventeen) {
setTitle("Halotan Hepatotoksisitesi");
Twentytwo twentytwo = new Twentytwo();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,twentytwo).commit();
}
else if (id == R.id.twoeigteen) {
setTitle("Bupivakain Kondroliz");
Twentythree twentythree = new Twentythree();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,twentythree).commit();
}
else if (id == R.id.twonineteen) {
setTitle("Yağ Embolisi");
Twentyfour twentyfour = new Twentyfour();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,twentyfour).commit();
}
else if (id == R.id.twotwenty) {
setTitle("Genel Anestezik");
Twentyfive twentyfive = new Twentyfive();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,twentyfive).commit();
}
else if (id == R.id.twotwentyone) {
setTitle("NDİ - ADH");
Twentysix twentysix = new Twentysix();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,twentysix).commit();
}
else if (id == R.id.twotwentytwo) {
setTitle("Glascow Koma");
Twentyseven twentyseven = new Twentyseven();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,twentyseven).commit();
}
else if (id == R.id.twotwentythree) {
setTitle("Hipovolemi");
Twentyeight twentyeight = new Twentyeight();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,twentyeight).commit();
}
else if (id == R.id.twotwentyfour) {
setTitle("Atrakuryum Bezilat");
Twentynine twentynine = new Twentynine();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,twentynine).commit();
}
else if (id == R.id.twotwentyfive) {
setTitle("SempatoadrenalHiperaktivasyon");
Thirty thirty = new Thirty();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,thirty).commit();
}
else if (id == R.id.twotwentysix) {
setTitle("CPR Trakeal");
Thirtyone thirtyone = new Thirtyone();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,thirtyone).commit();
}
else if (id == R.id.twotwentyseven) {
setTitle("Gravimetrik Etki");
Thirtytwo thirtytwo = new Thirtytwo();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,thirtytwo).commit();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout );
// drawer.closeDrawer(GravityCompat.START);
ConstraintLayout constraintLayout = findViewById(R.id.drawer_layoutd);
return true;
}
}
activty_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/baslik"
android:textSize="20sp"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:paddingTop="60dp"
android:id="#+id/text"
/>
</ScrollView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bir">
</FrameLayout>
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer"
app:itemTextColor="#color/colorPrimaryDark"/>
</androidx.drawerlayout.widget.DrawerLayout>
You must set your code of Justification_Mode in if condition because min API level is 26.
Kotlin code:
if (Build.VERSION.SDK_INT >= 26) {
tv.justificationMode = JUSTIFICATION_MODE_INTER_WORD
}
Java code:
if (Build.VERSION.SDK_INT >= 26) {
tv.setJustificationMode(JUSTIFICATION_MODE_INTER_WORD)
}
import android.content.Intent;
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.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
TextView textViewId, textViewUsername, textViewEmail, textViewGender;
#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);
//add this line to display menu1 when the activity is loaded
//displaySelectedScreen(R.id.nav_menu1);
if (!SharedPrefManager.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, Login.class));
}
textViewId = (TextView) findViewById(R.id.textViewId);
textViewUsername = (TextView) findViewById(R.id.textViewUsername);
textViewEmail = (TextView) findViewById(R.id.textViewEmail);
textViewGender = (TextView) findViewById(R.id.textViewGender);
//getting the current user
User user = SharedPrefManager.getInstance(this).getUser();
//setting the values to the textviews
textViewId.setText(String.valueOf(user.getId()));
textViewUsername.setText(user.getUsername());
textViewEmail.setText(user.getEmail());
textViewGender.setText(user.getGender());
//when the user presses logout button
//calling the logout method
findViewById(R.id.buttonLogout).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
SharedPrefManager.getInstance(getApplicationContext()).logout();
}
});
}
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 itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.staff_link:
fragment = new Staff_layout();
break;
case R.id.student_link:
fragment = new Student_layout();
break;
case R.id.vehicle_link:
fragment = new Vehicle_layout();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}
}
this is my MainActivity and when the item is clicked it is not redirecting and not showing any logcat errors this is my XML file
<?xml version="1.0" encoding="utf-8"?>
<menu 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"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/student_link"
android:title="Student Register" />
<item
android:id="#+id/staff_link"
android:title="Staff Register" />
<item
android:id="#+id/vehicle_link"
android:title="Vehicle Register" />
</group>
</menu>
it doesn't show any response even the item is clicked
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Student_layout extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
return inflater.inflate(R.layout.student_layout, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle
savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different
fragments different titles
getActivity().setTitle("Menu 1");
}
}
when the student item is clicked is not redirecting to student fragment layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="student"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
is there anything i should rectify or this doesnt work?
Switch fragment correctly, Your are declaring fragment in switch case but you are switching fragment outside the case:
You can use this code
Fragment mCurrentLoadedFragment;
android.support.v4.app.FragmentManager mFragmentManager, fm;
FragmentTransaction mFragmentTransaction;
and the method is
public void switchContent(Fragment fragment) {
mCurrentLoadedFragment = fragment;
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.container, mCurrentLoadedFragment);
mFragmentTransaction.commit();
}
and call like this,
if (id == R.id.nav_home) {
switchContent(new HomeFragment());
}
I am relatively new to Coding but please bear with me. I am trying to put a Google Map in a navigation drawer. I figured the best way is to use fragments but despite my various attempts I keep getting this error: "Error:(35, 62) error: incompatible types: MapsActivity cannot be converted to Fragment".
I have two Activities
1. MainActiyity: where there's an error.
2. MapsActivity: which is the default Activity when choosing to create google maps app on Android studio new project creation.
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;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set to start with fragment
MapsActivity fragment = new MapsActivity();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
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) 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();
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_building) {
MapsActivity fragment = new MapsActivity();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_map) {
} else if (id == R.id.nav_timetable) {
} else if (id == R.id.nav_noticeboard) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_placeholder) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Also, the word 'fragment' in fragmentTransaction.replace(R.id.fragment_container, fragment);
is underlined red.
I have tried to find different tutorials and guides but nothing solved my issue.
You can't do a FragmentTransaction with an Activity.
In order to use a Google Map in a NavigationDrawer, use a Fragment that extends SupportMapFragment, and add all of the functionality that your MapsActivity class currently has.
Use this to start with:
public class MapsFragment extends SupportMapFragment
implements OnMapReadyCallback {
GoogleMap mGoogleMap;
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
}
Then in the Activity, change this to use the Fragment:
// Set to start with fragment
MapsFragment fragment = new MapsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
I'm just new on Android Studio so please bear with me. I created two fragments named locate_before and locate_after. I have a button with an id of trigger on my locate_before fragment. I want to switch to locate_after after clicking that button.
Here's my main activity. I used a frame container for my fragments. I already created a code for what I want named onSelectFragment but it does not work. It says "method onSelectFragment is never used"
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Button trigger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
locate_before fragment = new locate_before();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction(); //check this out
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);
}
public void onSelectFragment(View v){
Fragment newFragment;
if(v == findViewById(R.id.trigger)){
newFragment = new locate_after();
}
else{
newFragment = new locate_before();
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
#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;
}
}
locate_before fragment java that ofc extends Fragment
public locate_before () {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_locate_before, container, false);
// Inflate the layout for this fragment
return rootView;
}
}
locate_before xml file button
<Button
android:id="#+id/trigger"
android:layout_width="284dp"
android:layout_height="58dp"
android:text="View Car's Location"
android:layout_marginRight="24dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="0.633"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="133dp" />
locate_after java
public class locate_after extends Fragment {
public locate_after () {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_locate_after, container, false);
// Inflate the layout for this fragment
return rootView;
}
}
Thank you!
Your buttom seems to have no onClickListener.
Add android:onClick="onSelectFragment" in your XML or bind your Button and add an onClickListener in your OnCreate.
use onNavigationItemSelected() to navigate to fragment. below is the examples code
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getSupportFragmentManager();
if (id == R.id.nav_home) {
Fragment homeFragment = new HomeFragment();
fragmentManager.beginTransaction().replace(R.id.relative_layout_fragment1, homeFragment, homeFragment.getTag()).commit();
} else if (id == R.id.nav_logout) {
Toast.makeText(mContext, "logout", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
You have uncommited transaction after your onCreate()
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction(); //check this out
First of all, you are never using method OnSelectFragment().
In your OnCreate method add following
trigger = (Button) findViewById(R.id.trigger); //get Button
trigger.setOnClickListener(new View.OnClickListener() { // action to do when button is pressed
#Override
public void onClick(View view) {
if(before)
onSelectFragment(new locate_after());
else
onSelectFragment(new locate_before());
before = !before; //this makes it a switch
}
});
Declare attribute "before" along other attributes
boolean before = true;
And change your onSelectFragment method to following
public void onSelectFragment(Fragment newFragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
Check current displayed fragment and set your desired fragment accordingly. Try the below code.
Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_container);
if(!(fragment instanceof locate_before)) {
newFragment = new locate_after();
}
else{
newFragment = new locate_before();
}
getSupportFragmentManager().beginTransaction().replace(newFragment).commit();
navigation drawer, handling the back button to go to HomeFragment
This is SecurityFragment
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class SecurityFragment extends Fragment {
public SecurityFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_security, container, false);
}
}
This is the HomeFragment (When onBackPressed i just want the user to be directed to the homepage)current situation is that on onBackPressed the running application is destroyed
package sampleapp.razen.com.sampleapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.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.MenuItem;
import android.view.View;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.widget.Toast;
public class Menu extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
android.app.Fragment fragment = new MenuFragment(); // create a fragement object
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
//this the email icon on the home page
#Override
public void onClick(View view) {
String myEmail[]={"john#balloonventures.com"};
Intent sendMail = new Intent(Intent.ACTION_SEND);
sendMail.putExtra(Intent.EXTRA_EMAIL,myEmail);
sendMail.putExtra(Intent.EXTRA_SUBJECT,"(Type your subject)");
sendMail.setType("plain/text");
//incase you have to add something else put here
sendMail.putExtra(Intent.EXTRA_TEXT,"Your phone:+2547");
startActivity(sendMail);
}
});
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);
}
//taxi module
public void taxi_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.Taxi.class);
startActivity(timer);}
//host home module
public void hosthome_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.MainActivity.class);
startActivity(timer);}
//calling enterprenuers module
public void enter_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.SectionListView.class);
startActivity(timer);}
//calling UKV/ICV
public void ukvicv_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.UkvIcv_Home.class);
startActivity(timer);}
public void finacial_id(View view){
Intent finacial=new Intent(this,sampleapp.razen.com.sampleapp.FinacialHomePage.class);
startActivity(finacial);}
#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 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);
}
public void displayView(int viewId) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (viewId) {
case R.id.nav_12wks_program:
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.ExpandableListMainActivity.class);
startActivity(timer);
break;
case R.id.nav_emergency_contact:
Intent flow=new Intent(this,sampleapp.razen.com.sampleapp.EmergencyContact.class);
startActivity(flow);
break;
case R.id.nav_survey:
fragment = new SurveyFragment();
title = "Survey";
break;
case R.id.nav_psld:
fragment = new PsldFragment();
title = "Psld";
break;
case R.id.nav_security:
fragment = new SecurityFragment();
title = "All Volunteers Mu";
break;
case R.id.nav_ukv:
fragment = new UkvKiswaFragment();
title = "Ukv's kiswahili";
break;
case R.id.nav_agreement:
fragment = new AgreementFragment();
title = "Agreement ";
break;
case R.id.nav_njoro_geo:
fragment = new GeoNjoroFragment();
title = "Njoro Geography ";
break;
}
if (fragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
}
// set the toolbar title
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
} #SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displayView(item.getItemId());
return true;
}
}
Add your fragment transection to Fragment Backstack befor commit
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.addToBackStack( "tag" );
ft.commit();