I have a navigation drawer activity with fragments in it. Now how can I make the app to go directly to a fragment when that activity is opened? I don't want to show the content_main.xml (which is blank):
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_menu1:
fragment = new Menu1();
break;
case R.id.nav_menu2:
fragment = new Menu2();
break;
case R.id.nav_menu3:
fragment = new Menu3();
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);
}
in onCreate()
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);
You have some options.
1) Open activity_main.xml
And replace a line that includes layout=content_main with the layout that you actually want instead.
2) Just load the Fragment in onCreate like you would when you do click on the Navigation Drawer.
go to Activity onCreate method and put this
FragmentManager fm =getFragmentManager();
FragmentTransaction ft= fm.beginTransaction();
// the Second paramter is Object from your Fragment that you want to add it
ft.replace(R.id.activity_main ,fragmentObject );
ft.commit();
Related
I have an app developed like the following image:
So a fragment A with a menu. Clicking on the menu it will open a fragment B.
My problem is that, when I click on the back button, nothing happens, so I can not return from fragment B to fragment A, and I don't understand why.
This is my code:
Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final DrawerLayout drawer = findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
drawer.openDrawer(Gravity.LEFT);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentA fragmentA = new FragmentA();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.relativelayout_for_fragment, fragmentA, fragmentA.getTag()).commit();
getSupportActionBar().setTitle(getResources().getString(R.string.title));
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() == 0){
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
toggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
}else{
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
drawer.openDrawer(GravityCompat.START);
} else {
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
Fragment A (on click on the menu)
Fragment fragmentB = new FragmentB();
FragmentTransaction transaction = activity.getFragmentManager().beginTransaction();
transaction.replace(R.id.relativelayout_for_fragment, fragmentB);
transaction.addToBackStack(null);
transaction.commit();
Fragment B
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.share_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStack();
return true;
case R.id.menu_item_share:
String contenuto = "*" + titolo + "*" + "\n" + desc;
String textToShare = getResources().getString(R.string.Linc);
Intent intent = new Intent("android.intent.action.SEND");
intent.setType("text/plain");
intent.putExtra("android.intent.extra.TEXT", contenuto + "\n\n" + textToShare);
startActivity(Intent.createChooser(intent,
getResources().getString(R.string.sharing)));
return true;
}
return super.onOptionsItemSelected(item);
}
did you try this onBackPressed
override fun onBackPressed() {
val manager: FragmentManager = supportFragmentManager
if(manager.backStackEntryCount > 0){
manager.popBackStack()
}else{
super.onBackPressed()
}
}
In MainActivity
After
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Put
getSupportFragmentManager().popBackStack()
I created a slide menu (one which found in default in navigation drawer activity) under a tabbed activity. I can call a fragment from the slide menu choices like shown in the code below. My question is , how can I call an activity instead of a fragment. Can anyone help me on this? Here is the code
public class MainActivity extends AppCompatActivity
{
DrawerLayout drawerLayout;
NavigationView navigationView;
android.support.v4.app.FragmentManager FM;
FragmentTransaction FT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
navigationView = (NavigationView) findViewById(R.id.shitstuff);
FM = getSupportFragmentManager();
FT = FM.beginTransaction();
FT.replace(R.id.containerView, new TabFragment()).commit();
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_history) {
FragmentTransaction fragmentTransaction = FM.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new HistoryFragment()).commit();
}
else if (id == R.id.nav_gallery) {
FragmentTransaction fragmentTransaction = FM.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new GalaryFragment()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
android.support.v7.widget.Toolbar toolbar =(Toolbar)findViewById(R.id.toolbar);
ActionBarDrawerToggle toggle=new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.app_name,R.string.app_name);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
}
}
Simply call activity instead of a fragment.
If you are new to the Android, on below code "this" refers to a current activity, HistoryAcitvity is a new activity which is going to start. Before you write this code, create activity, and add that activity to manifest(if you do it in the android studio it does automatically).
if (id == R.id.nav_history) {
Intent historyActivity = new Intent(this ,HistoryAcitivity.class);
startActivity(historyActivity);
}
i have menu with two fragments. when i choose second fragment, i can move to third fragment with button.
MainActivity
drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
getSupportActionBar().setTitle("demo");
mSelectedId = savedInstanceState == null ? R.id.aboutConference : savedInstanceState.getInt("SELECTED_ID");
itemSelection(mSelectedId);
}
private void setToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
}
private void initView() {
mDrawer = (NavigationView) findViewById(R.id.main_drawer);
mDrawer.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
}
private void itemSelection(int mSelectedId) {
switch (mSelectedId) {
case R.id.aboutConference:
mDrawerLayout.closeDrawer(GravityCompat.START);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new FirstFragment());
fragmentTransaction.commit();
break;
case R.id.aboutDeveloper:
mDrawerLayout.closeDrawer(GravityCompat.START);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new SecondFragment());
fragmentTransaction.commit();
break;
}
}
Second fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =
inflater.inflate(R.layout.second_fragment, container, false);
Button button = (Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new ThirdFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return view;
}
When i press backbutton, it's working correctly.
second fragment
But if i move to third fragment, choose first fragment in menu and press backbutton, third fragment overlaps first fragment
problem
How i can resolve this problem?
UPDATE: i don't want that i can return from first fragment to third when i press back button.
As Shaishav and vishal told you need to put colorto your parent view of the fragment.
orelse you need to Override the onBackButton pressed method and make sure the remove the previous item from stack.
To check if item is there in the stack or not try the following code
fragmentManager1.getBackStackEntryCount()
I have a navigation drawer and when I click on one of the menus, I want the default content to disappear, but it just doesn't happen and when I click on a new menu it's still there.
This is really annoying, I've been trying to find solution the whole day and I'm going crazy now.
Please help me out, if you can. Thanks in advance!
I copy the whole code here. (p.s.: this is the first and last time I'm programming on Android, this is a nightmare...I just must do this now :/)
public class About extends AppCompatActivity {
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
ImageButton FAB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
FAB = (ImageButton) findViewById(R.id.imageButton);
FAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(About.this, SecondActivity.class);
startActivity(i);
//FAB click, call other thing...
}
});
navigationView = (NavigationView) findViewById(R.id.nav_view);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new ListViewFragment());
fragmentTransaction.commit();
setNavDrawer();
navigationView.setCheckedItem(R.id.nav_gallery);
}
private void setNavDrawer() {
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.nav_camera:
Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_SHORT).show();
ContentFragment fragment = new ContentFragment();
android.support.v4.app.FragmentTransaction f = getSupportFragmentManager().beginTransaction();
f.replace(R.id.content_frame, fragment);
f.commit();
return true;
// For rest of the options we just show a toast on click
case R.id.nav_gallery:
Toast.makeText(getApplicationContext(), "Whatever", Toast.LENGTH_SHORT).show();
UserFragment fragment2 = new UserFragment();
android.support.v4.app.FragmentTransaction f2 = getSupportFragmentManager().beginTransaction();
f2.replace(R.id.content_frame, fragment2);
f2.commit();
return true;
case R.id.nav_slideshow:
Toast.makeText(getApplicationContext(), "SOON", Toast.LENGTH_SHORT).show();
return true;
case R.id.nav_share:
Toast.makeText(getApplicationContext(), "SOON", Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(), "SOON", Toast.LENGTH_SHORT).show();
return true;
}
}
});
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.addDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.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.about, 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);
}
}
Use these code on menu click..
Fragment fragment = new ContentFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.remove(new CurrentFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
an also add these lines in xml
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Try this
Fragment fragment = new Fragment();
fragment.setRetainInstance(true);
fragment = new ContentFragment ();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
I copied a navigation drawer from
http://javatechig.com/android/navigation-drawer-android-example
But I'm having trouble managing the fragments, or rather the main content on the screen.
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = "Formulas";
getActionBar().setTitle(mTitle);
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("Formulas");
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.drawer_list_item, getResources().getStringArray(R.array.menus));
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
// Enabling Home button
getActionBar().setHomeButtonEnabled(true);
// Enabling Up navigation
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Getting an array of rivers
String[] menuItems = getResources().getStringArray(R.array.menus);
// Currently selected river
mTitle = menuItems[position];
// Creating a fragment object
WebViewFragment rFragment = new WebViewFragment();
// Passing selected item information to fragment
Bundle data = new Bundle();
data.putInt("position", position);
data.putString("url", getUrl(position));
rFragment.setArguments(data);
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, rFragment);
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
});
}
protected String getUrl(int position) {
switch (position) {
case 0:
return "http://javatechig.com";
case 1:
return "http://javatechig.com/category/android/";
case 2:
return "http://javatechig.com/category/blackberry/";
case 3:
return "http://javatechig.com/category/j2me/";
case 4:
return "http://javatechig.com/category/sencha-touch/";
case 5:
return "http://javatechig.com/category/phonegap/";
case 6:
return "http://javatechig.com/category/java/";
default:
return "http://javatechig.com";
}
}
How do I manage the fragment so that I can:
- Input either basic xml/java (so I don't have to bother about bundles) in the project
or
- replace the current fragment so that I can create my own and customize everything myself
Try Checking this answer ..
It ll help you setting-up & using the Navigation Drawer in a dynamic way...
https://stackoverflow.com/a/34244065/2457493
Hope this fulfills you query..
I assume this is the example code from the Android Project shipped with the SDK.
Your sample actually contains the code needed for swapping the fragments in the content pane of the Activity.
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, rFragment);
// Committing the transaction
ft.commit();
Your rFragment is the fragment that is going to be loaded. You can put this whole section in a method and pass your fragment to be loaded as an argument of that method, e.g.
private void replaceFragment(Fragment newFragment) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, newFragment);
ft.commit();
}
If your Fragment to be loaded needs data to be passed to it, you can use the Bundle. Your fragments might take different types of data, but the code above still applies. Call it after you have called setArguments() on your Fragment object.