How to implement default activity (fragment) on app load. (Drawer Layout) - java

I am using fragments and have successfully set up all the activities. Everything is fully functional.
My issue is that I can't seem to have a default layout or fragment class load when the app starts up initially.
I have tried a few methods with weird results. Here is my code from MainActivity.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
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();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
if (id == home) {
fragment = new Home();
} else if (id == services) {
fragment = new Services();
} else if (id == beforeAfter) {
fragment = new BeforeAfter();
} else if (id == staff) {
fragment = new Staff();
} else if (id == patientInfo) {
fragment = new Patient();
} else if (id == blog) {
fragment = new Blog();
} else if (id == contactUs) {
fragment = new Contact();
}
if (fragment != null) {
android.support.v4.app.FragmentManager fragmentManager =
getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.screen_area, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is my fragment code for Home.class
public class Home extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.home, null);
}
}
After editing my MainActivity java file and appending onCreate with
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.screen_area, new Home());
ft.commit();
It now works. I guess I was assigning the name of the XML layout page for Home fragment instead of the ID of the FrameLayout under content_main.

call the fragment in your onCreate
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new Fragment1());
ft.commit();

your code looks fine. I guess the problem is in your activity_main.xml
make sure you have only two childs inside the DrawerLayout
one for your main container and one the NavigationView
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/my_navigation_items" />
</android.support.v4.widget.DrawerLayout>
you need to show your fragments inside onCreate
FragmentTransaction mFragmentTransaction = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new YourFragment());
ft.commit(); //important

Related

How to coordinate a Navigation Drawer with a Buttom Navigation View

I'm fairly new to android dev. I'm checking the material design library and I've implemented a navigation drawer with a bottom navigation to navigate easily through fragments. Both components work just fine but I don't how to coordinate the navigation with both components. For example when a fragment is toggled on the navigation drawer it changed the layout but the button navigation selected item is not changed with it.
How can I solve this issue and link both components to work with each other and sync the changed selected item?
This is what my java file looks like and here's link for the whole project on GitHub: https://github.com/mreek/NavigationDrawer
Thank you in advance.
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private TextView appBarTV;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent= new Intent(this,IntroActivity.class);
startActivity(intent);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
appBarTV = findViewById(R.id.appbar_text_view);
ImageButton menuRight = findViewById(R.id.leftRight);
menuRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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);
BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = MainFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = AccountFragment.newInstance();
break;
case R.id.action_item3:
selectedFragment = SellFragment.newInstance();
break;
case R.id.action_item4:
selectedFragment = ChatFragment.newInstance();
break;
case R.id.action_item5:
selectedFragment = NotificationFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.f_container, selectedFragment);
transaction.commit();
return true;
}
});
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.f_container, MainFragment.newInstance());
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) {
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;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
drawer.closeDrawers();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
int id = item.getItemId();
if (id == R.id.nav_camera) {
MainFragment fragment = new MainFragment();
ft.replace(R.id.f_container, fragment);
ft.commit();
} else if (id == R.id.nav_gallery) {
//appBarTV.setText("Fragment With Tabs");
ChatFragment fragment = new ChatFragment();
ft.replace(R.id.f_container, fragment);
ft.commit();
} else if (id == R.id.nav_slideshow) {
AccountFragment fragmentTab = new AccountFragment();
ft.replace(R.id.f_container, fragmentTab);
ft.commit();
} else if (id == R.id.nav_share) {
Toast.makeText(this, "Partager", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_send) {
Toast.makeText(this, "Rate 5 stars", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
<?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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/app_bar_main" />
<FrameLayout
android:id="#+id/f_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="3dp"
android:background="#color/white"
app:itemIconTint="#color/blue"
app:itemTextColor="#color/blue"
app:menu="#menu/bottom_navigation_items" />
</RelativeLayout>
<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_main"
app:menu="#menu/activity_main_drawer"
app:itemTextColor="#color/black"/>
</android.support.v4.widget.DrawerLayout>
First of all you should avoid recreating fragments when user selected a tab from bottom navigation. You should keep your fragments as private variables:
private DrawerLayout drawer;
private BottomNavigationView bottomNavigationView;
private MainFragment mainFragment = MainFragment.newInstance();
private AccountFragment accountFragment = AccountFragment.newInstance();
private SellFragment sellFragment = SellFragment.newInstance();
private ChatFragment chatFragment = ChatFragment.newInstance();
private NotificationFragment notificationFragment = NotificationFragment.newInstance();
When user selects a tab just swich to that fragment:
bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_announces:
selectedFragment = mainFragment;
break;
case R.id.action_account:
selectedFragment = accountFragment;
break;
case R.id.action_sell:
selectedFragment = sellFragment;
break;
case R.id.action_chat:
selectedFragment = chatFragment;
break;
case R.id.action_notifications:
selectedFragment = notificationFragment;
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (selectedFragment != null) {
transaction.replace(R.id.f_container, selectedFragment);
transaction.commit();
}
return true;
});
When user selects a tab using navigation menu swich to required fragment:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawer.closeDrawers();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (item.getItemId()) {
case R.id.nav_announces:
bottomNavigationView.setSelectedItemId(R.id.action_announces);
ft.replace(R.id.f_container, mainFragment);
break;
case R.id.nav_account:
bottomNavigationView.setSelectedItemId(R.id.action_account);
ft.replace(R.id.f_container, accountFragment);
break;
case R.id.nav_sell:
bottomNavigationView.setSelectedItemId(R.id.action_sell);
ft.replace(R.id.f_container, sellFragment);
break;
case R.id.nav_chat:
bottomNavigationView.setSelectedItemId(R.id.action_chat);
ft.replace(R.id.f_container, chatFragment);
break;
case R.id.nav_notifications:
bottomNavigationView.setSelectedItemId(R.id.action_notifications);
ft.replace(R.id.f_container, notificationFragment);
break;
}
ft.commit();
return true;
}
I have forked your repo and migrated it to AndroidX before fixing it on a new branch called androidx. I made a pull request to you. You can accept and try it.
try this code:
private void setupNavDrawer(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()){
case R.id.nav_gallery:
fragment = new GalleryFragment();
break;
case R.id.nav_share:
fragment = new ShareFragment();
break;
default:
fragment = new GalleryFragment();
break;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
//if checked - set title menu
item.setChecked(true);
setTitle(item.getTitle());
mDrawerLayout.closeDrawers();
return true;
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
............//nav
setupNavDrawer(navigationView);
}

How to directly select fragment class on launch of the MainActivity?

I'm trying to figure out how to directly display the memberFragment.class fragment instead of the MainActivity from showing without selecting it on the navigation bar.
My Code:
public class AdminActivity extends AppCompatActivity {
private DrawerLayout mdrawerl;
private ActionBarDrawerToggle mtoggle;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
auth = FirebaseAuth.getInstance();
mdrawerl = (DrawerLayout) findViewById(R.id.drawer);
mtoggle = new ActionBarDrawerToggle(this,mdrawerl,R.string.open, R.string.close);
mdrawerl.addDrawerListener(mtoggle);
NavigationView nvDrawer = (NavigationView) findViewById(R.id.nv) ;
mtoggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupDrawerContent(nvDrawer);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mtoggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void selectItemDrawer(MenuItem menuItem) {
auth = FirebaseAuth.getInstance();
Fragment myFragment = null;
Class fragmentClass;
switch (menuItem.getItemId()){
case R.id.signout:
auth.getInstance().signOut();
Intent i = new Intent(AdminActivity.this, LoginActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
return;
}
switch (menuItem.getItemId()){
case R.id.members:
fragmentClass = memberFragment.class;
break;
case R.id.transactions:
fragmentClass = transaction.class;
break;
default:
fragmentClass = member.class;
}
try {
myFragment = (Fragment) fragmentClass.newInstance();
}
catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flcontent,myFragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mdrawerl.closeDrawers();
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectItemDrawer(item);
return false;
}
});
}
The problem here is that when launching the activity, it would launch on the Activity itself instead of the fragment memberFragment as the default.
Try with below code, put below code inside your onCreate() :
memberFragment frag = new memberFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.flcontent, frag)
.commit();
Full code should be like this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
auth = FirebaseAuth.getInstance();
mdrawerl = (DrawerLayout) findViewById(R.id.drawer);
mtoggle = new ActionBarDrawerToggle(this,mdrawerl,R.string.open, R.string.close);
mdrawerl.addDrawerListener(mtoggle);
NavigationView nvDrawer = (NavigationView) findViewById(R.id.nv) ;
mtoggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupDrawerContent(nvDrawer);
memberFragment frag = new memberFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.flcontent, frag)
.commit();
}
You can not launch a fragment without activity but you can launch fragment suddenly after activity launch.
To do that do simple fragment transaction on activity onCreate and most important part select menu item from NavigationView.
Copy past below code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
auth = FirebaseAuth.getInstance();
mdrawerl = (DrawerLayout) findViewById(R.id.drawer);
mtoggle = new ActionBarDrawerToggle(this,mdrawerl,R.string.open,
R.string.close);
mdrawerl.addDrawerListener(mtoggle);
NavigationView nvDrawer = (NavigationView) findViewById(R.id.nv) ;
mtoggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupDrawerContent(nvDrawer);
memberFragment frag = new memberFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.flcontent, frag)
.commit();
nvDrawer.getMenu().getItem(0).setChecked(true);
}

Restoring fragment state in Navigation Drawer activity

I am having problems restoring the states of the different fragments in the NavigationDrawer activity. I have 4 tabs which calls 4 different fragments. When I switch back I want to restore the previous state. I have been trying but cannot seem to be able to implement addToBackStack when restoring states. The following code again reloads the fragments.
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
homeFragment fragment=new homeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
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);
}
#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) {
homeFragment fragment=new homeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.addToBackStack("home").commit();
} else if (id == R.id.nav_gallery) {
techNews fragment=new techNews();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.addToBackStack("tech").commit();
} else if (id == R.id.nav_slideshow) {
nepal fragment=new nepal();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_manage) {
mobilePrice fragment=new mobilePrice();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
} 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;
}
}
homeFragment.java
public class homeFragment extends Fragment {
private RecyclerView rvItem;
private updateAdapter updateLatestPage;
public homeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setContentView(R.layout.activity_main);
View rootview=inflater.inflate(R.layout.fragment_home,container,false);
rvItem = (RecyclerView)rootview.findViewById(R.id.rvItem);
rvItem.setHasFixedSize(true);
final LinearLayoutManager manager = new LinearLayoutManager(getContext());
rvItem.setLayoutManager(manager);
String url = "http://www.gadgetsinnepal.com.np/wp-json/wp/v2/posts/?page=";
updateLatestPage = new updateAdapter(rvItem, getContext(), url, manager);
updateLatestPage.fetchAndPut();
return rootview;
}
}
TechNews.java
public class techNews extends Fragment {
private RecyclerView rvItem;
private updateAdapter updateLatestPage;
public techNews() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setContentView(R.layout.activity_main);
View rootview=inflater.inflate(R.layout.fragment_home,container,false);
rvItem = (RecyclerView)rootview.findViewById(R.id.rvItem);
rvItem.setHasFixedSize(true);
final LinearLayoutManager manager = new LinearLayoutManager(getContext());
rvItem.setLayoutManager(manager);
String url = "http://www.gadgetsinnepal.com.np/wp-json/wp/v2/posts/?categories=1&&page=";
updateLatestPage = new updateAdapter(rvItem, getContext(), url, manager);
updateLatestPage.fetchAndPut();
return rootview;
}
}
All other fragments are similar. How do I go about restoring the states of each fragment?

How to create a Image gallery inside a fragment in Android Studio

So I've created a Gallery Fragment in my navigation drawer. Now my question is, how do I create an image gallery once you clicked the "gallery" in my drawer step by step using gridView. Other tutorials in the internet uses MainActivity, which in my case, I need to put it in my GalleryFragment, but a fragment is in a whole new level. My codes are below.
for my MainActivity.java:
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 the fragment initially
MainFragment fragment = new MainFragment();
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();
//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_home) {
//Set the fragment initially
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
// Handle the camera action
} else if (id == R.id.nav_gallery) {
GalleryFragment fragment = new GalleryFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_about) {
AboutFragment fragment = new AboutFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_contact) {
ContactFragment fragment = new ContactFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
GalleryFragment.java:
public class GalleryFragment extends Fragment {
public GalleryFragment() {
// 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_gallery, container, false);
}
}
fragment_gallery.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.guitarista.citem.GalleryFragment">
<!-- TODO: Update blank fragment layout
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
-->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GALLERY"
android:padding="8dp"
android:textColor="#fff"
android:background="#color/colorPrimary"
android:textSize="28sp"
android:id="#+id/main_button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Fragment mDrawer menu

I am building an simply webview app with mDrawer menu, and it work's like a charm on 3.0+ android, but i want it to work with versions under 3. I have read about v4 support and i added it to the project. Application was a Activity then i changed to FragmentActivity because off support library . Sorry for my English.
Here's the code.
public class MainActivity extends FragmentActivity {
private LayoutInflater mInflater;
private DrawerLayout mDrawerLayout;
WebView browser;
// ListView represents Navigation Drawer
private ListView mDrawerList;
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
private ActionBarDrawerToggle mDrawerToggle;
private String mTitle = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView browser = (WebView) findViewById(R.id.webView1);
browser.loadUrl("");
browser.setWebViewClient(new WebViewClient());
WebSettings webSettings = browser.getSettings();
webSettings.setJavaScriptEnabled(true);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
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("Menu");
invalidateOptionsMenu();
}
};
browser.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
// 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
// Passing selected item information to fragment
Bundle data = new Bundle();
data.putInt("position", position);
data.putString("url", getUrl(position));
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
public void onBackStackChanged() {
if(getFragmentManager().getBackStackEntryCount() == 0) finish();
}
});
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
});
}
The problem is in
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
public void onBackStackChanged() {
if(getFragmentManager().getBackStackEntryCount() == 0) finish();
}
});
The method addOnBackStackChangedListener(FragmentManager.OnBackStackChangedListener) in the type FragmentManager is not applicable for the arguments (new FragmentManager.OnBackStackChangedListener(){})
You're importing the wrong FragmentManager.OnBackStackChangedListener.
What you have
import android.app.FragmentManager.OnBackStackChangedListener;
What you should have
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
use getSupportFragmentManager() instead of getFragmentManager.
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() == 0)
finish();
}
});

Categories