How to Display Fragments in Main Activity from Navigation Drawer? - java

I have three Fragments that I am trying to display by clicking the appropriate option from a Navigation Drawer. I have the Navigation Drawer displaying and opening/closing fine. But I can't get any of the Fragments to display in the Activity. The main screen just stays blank whenever I click an option. There are no compilation errors. I am new to Android development and also Java dev, and I've been trying to complete this project for a month so it will be finished as soon as I can get this to work. You may see some instances of redundant code, because I just wanted to try anything that could work and I am not sure what to delete, so any clarification on that would help too.
The Fragments should be displayed as results in a RecyclerView.
MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nView;
private ActionBarDrawerToggle toggle;
private RequestQueue queue;
private List<ATM> atmList;
private RecyclerView atmView;
private AtmRecyclerViewAdapter atmRecyclerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find drawer layout
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// Find drawer view
nView = (NavigationView) findViewById(R.id.nav_view);
// Set up drawer view
setupDrawerContent(nView);
// Not sure what this does
nView.setNavigationItemSelectedListener(this);
toggle = new ActionBarDrawerToggle(
this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
// Tie DrawerLayout events to the ActionBarDrawerToggle
mDrawer.addDrawerListener(toggle);
queue = Volley.newRequestQueue(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
toggle.onConfigurationChanged(newConfig);
}
#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.
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
if (toggle.onOptionsItemSelected(item)) {
return true;
}
/* 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_items_catalog) {
// Handle the items catalog action
} else if (id == R.id.nav_items_search) {
} else if (id == R.id.nav_atms) {
/*
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Constants.atmURL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject atmObj = response.getJSONObject(i);
ATM atm = new ATM();
atm.setAtmId(atmObj.getString("atmid"));
atm.setTitle(atmObj.getString("title"));
atm.setAddress(atmObj.getString("address"));
atm.setType(atmObj.getString("type"));
atm.setLat(atmObj.getDouble("lat"));
atm.setLon(atmObj.getDouble("lon"));
atm.setOnlineStatus(atmObj.getString("onlineStatus"));
atmList.add(atm);
// Log.d("ATM Statuses", atmList.get(i).getOnlineStatus());
}
// atmView = findViewById(R.id.atmRecyclerView);
// atmView.setHasFixedSize(true);
// atmView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
atmRecyclerViewAdapter = new AtmRecyclerViewAdapter
(MainActivity.this, atmList);
atmView.setAdapter(atmRecyclerViewAdapter);
atmRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
*/
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_items_catalog:
fragmentClass = ShowItems.class;
// TODO: Find out how to show the fragments in these calls
// fragment.listItems(???);
break;
case R.id.nav_items_search:
fragmentClass = SearchItems.class;
break;
case R.id.nav_atms:
fragmentClass = ShowATMs.class;
/*
atmView = findViewById(R.id.atmRecyclerView);
atmView.setHasFixedSize(true);
atmView.setLayoutManager(new LinearLayoutManager(this));
*/
break;
default:
fragmentClass = ShowItems.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
mDrawer.closeDrawers();
}
}
ShowATMs method - Want to show a list of ATM Objects in a RecyclerView format:
public class ShowATMs extends Fragment {
private RecyclerView atmView;
private AtmRecyclerViewAdapter atmRecyclerViewAdapter;
private RequestQueue queue;
// TODO: NEED TO CREATE A VIEW THAT WILL INFLATE CORRECT LAYOUT HERE
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Is this line needed?
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.atm_view, container, false);
atmView = rootView.findViewById(R.id.atmRecyclerView);
atmView.setHasFixedSize(true);
atmView.setLayoutManager(new LinearLayoutManager(getContext()));
final List<ATM> atmList = new ArrayList<>();
queue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Constants.atmURL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject atmObj = response.getJSONObject(i);
ATM atm = new ATM();
atm.setAtmId(atmObj.getString("atmid"));
atm.setTitle(atmObj.getString("title"));
atm.setAddress(atmObj.getString("address"));
atm.setType(atmObj.getString("type"));
atm.setLat(atmObj.getDouble("lat"));
atm.setLon(atmObj.getDouble("lon"));
atm.setOnlineStatus(atmObj.getString("onlineStatus"));
atmList.add(atm);
// Log.d("ATM Statuses", atmList.get(i).getOnlineStatus());
}
atmRecyclerViewAdapter = new AtmRecyclerViewAdapter
(getContext(), atmList);
atmView.setAdapter(atmRecyclerViewAdapter);
atmRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
return rootView;
}
}
XML files
activity_main.xml:
<?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">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment android:name="com.camelr.bilal.camelrecommerceproject.Fragments.ShowATMs"
android:id="#+id/ATMs"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="0dp"
tools:layout="#layout/atm_view" />
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/flContent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!--<include
layout="#layout/app_bar_main"
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"
android:background="#color/colorPrimary"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
atm_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<!--
tools:context=".MainActivity"
tools:showIn="#layout/activity_main">
-->
<android.support.v7.widget.RecyclerView
android:id="#+id/atmRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
I have two other Fragments that I set up a little differently but just showing the one for ATMs because I feel it is the closest to working. I appreciate the time and help any of the experienced programmers here can give me. If there is any more information that I should provide to help my situation, let me know. Thank you

Related

How can i setup a base drawer for all activities

I have read a lot of answers here but could not manage to do it. I want all of my activities to have a drawer. Inside the drawer i have a ListView which contains all of the activities that the drawer should open. This is the implementation of the drawer:
public abstract class DrawerActivity extends BaseActivity {
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.base_drawer_layout);
drawerLayout = findViewById(R.id.drawer_layout);
drawerList = findViewById(R.id.left_drawer);
final ArrayList<String> elements = new ArrayList<>();
elements.add("My tasks");
elements.add("Issues");
drawerList.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, elements));
drawerList.setOnItemClickListener(createOnDrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view)
{
getSupportActionBar().setTitle("TITLE");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView)
{
getSupportActionBar().setTitle("Title");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
drawerLayout.addDrawerListener(drawerToggle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (drawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
protected abstract DrawerItemClickListener createOnDrawerItemClickListener();
protected ListView drawerList()
{
return drawerList;
}
protected DrawerLayout drawerLayout()
{
return drawerLayout;
}
}
This is the drawer layout xml file
<?xml version="1.0" encoding="utf-8"?>
<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 -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#274"/>
</android.support.v4.widget.DrawerLayout>
Lets say i have currently two activities, My Tasks and Issues and both of them extend DrawerActivity. If i am in the Issues activity, how can i open the My Tasks activity through that drawer?
All activities that extend DrawerActivity implements createOnDrawerItemClickListener() which inside creates a new fragment with the layout of the the activity that implements DrawerActivity, which i'm pretty sure is wrong.
Example implementation:
#Override
protected DrawerItemClickListener createOnDrawerItemClickListener()
{
return new DrawerItemClickListener(position ->
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, new TaskFragment()).commit();
drawerList().setItemChecked(position, true);
drawerLayout().closeDrawer(drawerList());
});
}
And the DrawerItemClickListener:
public class DrawerItemClickListener implements ListView.OnItemClickListener {
private FragmentStrategy fragmentStrategy;
public DrawerItemClickListener(final FragmentStrategy fragmentStrategy)
{
this.fragmentStrategy = fragmentStrategy;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
fragmentStrategy.showFragment(position);
}
public interface FragmentStrategy {
void showFragment(final int position);
}
}
How can i make this work?
In your case adding fragment will be the best solution.
create a fragment BlankFragment.java
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
and create fragment_black.xml
<FrameLayout 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.above_inc.shyam.drawer.BlankFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
now replace your method
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new BlankFragment();
} 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) {
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
add below code in your content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.above_inc.shyam.drawer.MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
you can also add more fragment to other options same as camera in above code

android statusbar hiding navigationdrawer

I have a navigation drawer with this code:
<?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:fitsSystemWindows="true"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:openDrawer="start">
<!--<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"-->
<!--android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">-->
<!--<android.support.v7.widget.Toolbar android:id="#+id/toolbar"-->
<!--android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"-->
<!--android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />-->
<!--</android.support.design.widget.AppBarLayout>-->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent" >
</FrameLayout>
<!--<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"-->
<!--android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">-->
<!--</android.support.design.widget.AppBarLayout>-->
<!--<include-->
<!--layout="#layout/app_bar_home_page"-->
<!--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"
app:headerLayout="#layout/nav_header_home_page"
app:menu="#menu/activity_home_page_drawer"
app:insetForeground="#4000"/>
</android.support.v4.widget.DrawerLayout>
I also set my style v21 with this:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">#android:color/transparent</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="windowActionModeOverlay">true</item>
</style>
But my problem is that the actionbar is always over my navigationdrawer, hiding his top side. here is a screenshot:
As you can see my actionbar is hiding the nav drawer.
How can I solve this? Any help will be appreciated.
Thanks all
PS:
this is what I want to achieve, it's the first image I found on the net.
EDIT:
note the images please, my aim is not the same of the "duplicate". He wanted to set his List below an header, I want to hide the statusbar with my drawer
EDIT2:
I'm back to the origins, now the navigation drawer is simply below the actionBar. This is my java code:
public class HomePageActivity extends AppCompatActivity implements IHomePage {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle mDrawerToggle;
private ActionBar ab;
private boolean isDetail = false;
private int lastSelected = 0;
#Override
protected void onResume() {
super.onResume();
if(mDrawerToggle != null) {
mDrawerToggle.syncState();
}
if(navigationView != null){
navigationView.getMenu().getItem(0).setChecked(true);
} else{
initDrawer();
navigationView.getMenu().getItem(0).setChecked(true);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
navigationView = (NavigationView) findViewById(R.id.nav_view);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
initActionBar() ;
initDrawer();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
PreferitiFragment fragment = new PreferitiFragment();
fragmentTransaction.add(R.id.content_frame, fragment);
fragmentTransaction.commit();
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
private void initActionBar() {
ab = getSupportActionBar();
if (ab == null) {
Toast.makeText(this, "no", Toast.LENGTH_SHORT).show();
return;
}
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
}
private void initDrawer() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
lastSelected = id;
switch (id){
case R.id.nav_favorite:
setFragment(new PreferitiFragment());
break;
case R.id.nav_search:
setFragment(new CercaPaeseFragment());
break;
case R.id.nav_settings:
setFragment(new ImpostazioniFragment());
break;
case R.id.nav_guida:
setFragment(new GuidaFragment());
break;
default:
setFragment(new PreferitiFragment());
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
mDrawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
// mDrawerToggle.syncState();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
// mDrawerToggle.syncState();
}
};
drawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
public void showDetails(UUID idPharmacy) {
isDetail = true;
setFragment(new DettagliFragment());
}
#Override
public void onBackPressed() {
if (isDetail) {
if(lastSelected == R.id.nav_search) {
setFragment(new CercaPaeseFragment());
} else if(lastSelected == R.id.nav_favorite){
setFragment(new PreferitiFragment());
}
} else {
super.onBackPressed();
}
}
private void setFragment(Fragment fragment){
IMyFragments iMyFragments = (IMyFragments) fragment;
ab.setTitle(iMyFragments.getTitle());
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.content_frame, fragment);
fragmentTransaction.commit();
}
}
And this is my home page layout:
<?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"
tools:openDrawer="start">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent" >
</FrameLayout>
<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:headerLayout="#layout/nav_header_home_page"
app:menu="#menu/activity_home_page_drawer" />
</android.support.v4.widget.DrawerLayout>
On android.support.v4.widget.DrawerLayout You can try adding
android:paddingTop="?attr/actionBarSize"
Here is a simalar Question Android Navigation Drawer and windowActionBarOverlay = true
Or you can hide the action bar
from https://stackoverflow.com/a/22891560/1815624
Very simple.
getActionbar().hide();
getActionbar().show();
For the last part about the separator
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
To add vertical separator, switch the layout_width and layout_height
values
Or to put the drawer on top of the ActionbBar you can try the answer from:
https://stackoverflow.com/a/26174941/1815624
Below is some detailed steps for you to do that.
First, create a xml named "decor.xml" or anything you like. Only put
the DrawerLayout and the drawer in. The "FrameLayout" below is just a
container. We will use it to wrap your activity's content.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout ...>
<FrameLayout android:id="#+id/container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<fragment android:name="com...."
android:layout_gravity="start"
android:id="#id/navigation"
android:layout_width="#dimen/navigation_menu_width"
android:layout_height="fill_parent" />
</android.support.v4.widget.DrawerLayout>
and then remove the DrawerLayout in your main layout. Now the layout
of your main activity should look like
<RelativeLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
...
</RelativeLayout>
we assume that the main activity's layout is named "main.xml".
in your MainActivity, write as the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Inflate the "decor.xml"
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DrawerLayout drawer = (DrawerLayout) inflater.inflate(R.layout.decor, null); // "null" is important.
// HACK: "steal" the first child of decor view
ViewGroup decor = (ViewGroup) getWindow().getDecorView();
View child = decor.getChildAt(0);
decor.removeView(child);
FrameLayout container = (FrameLayout) drawer.findViewById(R.id.container); // This is the container we
defined just now.
container.addView(child);
// Make the drawer replace the first child
decor.addView(drawer);
// Do what you want to do.......
}
Now you've got a DrawerLayout which can slide over the ActionBar. But
you might find it covered by status bar. You might need to add a
paddingTop to the Drawer in order to fix that.
This is not ideal but it should help you... The white is the drawer the black is the main content and the blue is the title bar....
public class HomePageActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle mDrawerToggle;
private ActionBar ab;
private boolean isDetail = false;
private int lastSelected = 0;
#Override
protected void onResume() {
super.onResume();
if(mDrawerToggle != null) {
mDrawerToggle.syncState();
}
// if(navigationView != null){
// navigationView.getMenu().getItem(0).setChecked(true);
// } else{
// initDrawer();
// navigationView.getMenu().getItem(0).setChecked(true);
// }
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
navigationView = (NavigationView) findViewById(R.id.nav_view);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
initActionBar() ;
initDrawer();
// FragmentManager fragmentManager = getFragmentManager();
// FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// PreferitiFragment fragment = new PreferitiFragment();
// fragmentTransaction.add(R.id.content_frame, fragment);
// fragmentTransaction.commit();
mDrawerToggle.syncState();
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
navigationView = (NavigationView) findViewById(R.id.nav_view);
DrawerLayout drawer = (DrawerLayout) inflater.inflate(R.layout.drawer_layout, null);
// HACK: "steal" the first child of decor view
ViewGroup decor = (ViewGroup) getWindow().getDecorView();
View child = decor.getChildAt(0);
decor.removeView(child);
FrameLayout container = (FrameLayout) drawer.findViewById(R.id.content_frame); // This is the container we defined just now.
container.addView(child);
decor.addView(drawer);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
private void initActionBar() {
ab = getSupportActionBar();
if (ab == null) {
Toast.makeText(this, "no", Toast.LENGTH_SHORT).show();
return;
}
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
}
private void initDrawer() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
lastSelected = id;
// switch (id){
// case R.id.nav_favorite:
// setFragment(new PreferitiFragment());
// break;
//
// case R.id.nav_search:
// setFragment(new CercaPaeseFragment());
// break;
//
// case R.id.nav_settings:
// setFragment(new ImpostazioniFragment());
// break;
//
// case R.id.nav_guida:
// setFragment(new GuidaFragment());
// break;
// default:
// setFragment(new PreferitiFragment());
// break;
// }
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
mDrawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
android.R.drawable.ic_btn_speak_now,
R.string.open,
R.string.close
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
// mDrawerToggle.syncState();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
// mDrawerToggle.syncState();
}
};
drawerLayout.setDrawerListener(mDrawerToggle);
}
// #Override
// public void showDetails(UUID idPharmacy) {
//
// isDetail = true;
// setFragment(new DettagliFragment());
// }
// #Override
// public void onBackPressed() {
// if (isDetail) {
// if(lastSelected == R.id.nav_search) {
// setFragment(new CercaPaeseFragment());
// } else if(lastSelected == R.id.nav_favorite){
// setFragment(new PreferitiFragment());
// }
// } else {
// super.onBackPressed();
// }
// }
// private void setFragment(Fragment fragment){
//
//
// IMyFragments iMyFragments = (IMyFragments) fragment;
// ab.setTitle(iMyFragments.getTitle());
//
// FragmentManager fragmentManager = getFragmentManager();
// FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// fragmentTransaction.add(R.id.content_frame, fragment);
// fragmentTransaction.commit();
// }
}

Cannot customize Navigation Drawer

I need to customize my navigation drawer like following.
Currently I was able to add following part.
No matter how hard I tried to add another text fields, edit texts and images, I couldn't do it.
Here is my sample code.
This is how I added fields in strings.xml
<string-array name="titles">
<item>Hotel</item>
<item>Historical Sites</item>
<item>Shopping</item>
<item>Restaurant</item>
<item>Attractions</item>
<item>wild Life</item>
<item>Tour Service</item>
</string-array>
<array name="icons">
<item>#drawable/ic_hotel</item>
<item>#drawable/ic_historical</item>
<item>#drawable/ic_shopping</item>
<item>#drawable/ic_resturant</item>
<item>#drawable/ic_attraction</item>
<item>#drawable/ic_wildlife</item>
<item>#drawable/ic_tourservices</item>
</array>
Here is my mainactivity.xml
<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">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<!-- Listview to display slider menu -->
<include layout="#layout/drawer_layout" />
Here is my list_item.xml
<?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="48dp"
android:padding="5dp" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:textColor="#ffffff"
android:textSize="20sp" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
</RelativeLayout>
Here is my CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context; List<RowItem> rowItem;
CustomAdapter(Context context, List<RowItem> rowItem) {
this.context = context;
this.rowItem = rowItem;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
RowItem row_pos = rowItem.get(position);
// setting the image resource and title
imgIcon.setImageResource(row_pos.getIcon());
txtTitle.setText(row_pos.getTitle());
return convertView;
}
#Override
public int getCount() {
return rowItem.size();
}
#Override
public Object getItem(int position) {
return rowItem.get(position);
}
#Override
public long getItemId(int position) {
return rowItem.indexOf(getItem(position));
}
}
Here is my mainactivity.java
public class Extract extends ActionBarActivity {
String[] menutitles;
TypedArray menuIcons;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_extract);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId( i, -1));
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.app_name,R.string.app_name)
{
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu(); }
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new MapFragment();
break;
case 1:
fragment = new hotel();
break;
case 2:
fragment = new restaurant();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
// error in creating fragment
Log.e("Extract", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_extract, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default :
return super.onOptionsItemSelected(item);
}
}
/*** * Called when invalidateOptionsMenu() is triggered */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState(); }
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
Here is my drawer_layoout.xml
<?xml version="1.0" encoding="utf-8"?>
<DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/slider_list"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#000000"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:layout_weight="1" />
</DrawerLayout>
Please help me to add the image, two text views near image, horizontal line, and the edit text. Thanks in advance
In your MainActivity, add a new field for the LinearLayout, and assign value to it in onCreate()
private LinearLayout mLenear;
mLenear = (LinearLayout)findViewById(R.id.left_drawer);// inside onCreate
Then add following code inside onPrepareOptionsMenu
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mLenear);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
Then change your closeDrawer like this.
mDrawerLayout.closeDrawer(mLenear);
This should resolve your issue. :)
this will be the main layout that you will be using it contain two parts one is the main part which will have the layout of the main screen and the drawer_layout is the layout that has you navigation view layouts
So you will have to create drawer_layout as you want to display and just simply call it here
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/navigationDrawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
// you will have layout that you will use for your main activity or the activity where you are showing your navigation View
</FrameLayout>
// the drawer_layout will define your navigation View
<include layout="#layout/drawer_layout" />
</android.support.v4.widget.DrawerLayout>
In the activity you will get access to your drawer_layout and get access to your views using that object like
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.navigationDrawer);
// Example of getting your view object
ImageView yourImageView = (ImageView) drawerLayout.findViewById(R.id.imageView);
// you can access any your drawerView using that drawerLayout object

how to set default fragment of naviagationdrawer on oncreate activity

I tried a lot of fragment transaction ways but my default fragment is not launching while opening navigationdrawer activity.
public class MainActivity extends AppCompatActivity{
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private int mSelectedId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
toolbar.setNavigationIcon(R.drawable.nav_icon);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
navigationView = (NavigationView)findViewById(R.id.nvView);
setupDrawerContent(navigationView);
mSelectedId = R.id.home;
selectDrawerItem(mSelectedId);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem.getItemId());
return true;
}
});
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
public void selectDrawerItem(int mSelectedId) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
Class fragmentClass;
switch(mSelectedId) {
case R.id.home:
fragmentClass = Main.class;
break;
case R.id.orderhistory:
fragmentClass = Order_history.class;
break;
case R.id.profile:
fragmentClass = Profile.class;
break;
case R.id.contact:
fragmentClass = Contact.class;
break;
case R.id.polices:
fragmentClass = polices.class;
break;
default:
fragmentClass = Main.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.flContent, fragment);
fragmentTransaction.commit();
// Highlight the selected item, update the title, and close the drawer
// menuItem.setChecked(true);
// setTitle(menuItem.getTitle());
drawerLayout.closeDrawers();
}
}
Its still showing the activity first while launching. do pass suggestions so as i can move forward.
Activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
tools:context="in.co.blogspot.mellow.mellow.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id= "#+id/tool_bar"
layout= "#layout/tool_bar"></include>
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
Main.class
public class Main extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
public Main() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main,null);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
// Inflate the layout for this fragment
return rootView;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new p1();
case 1 : return new p2();
case 2 : return new p3();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
I think you can change a little your code.
Change your method selectDrawerItem in this way selectDrawerItem(int mSelectedId) so you can receive the id of the menu and not the menu so in onCreate() method you can do something like this
MainActivity
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private int mSelectedId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
navigationView = (NavigationView)findViewById(R.id.nvView);
setupDrawerContent(navigationView);
mSelectedId = R.id.orderhistory;
selectDrawerItem(mSelectedId);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem.getItemId());
return true;
}
});
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
public void selectDrawerItem(int mSelectedId) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
Class fragmentClass;
switch(mSelectedId) {
case R.id.home:
fragmentClass = Main.class;
break;
case R.id.orderhistory:
fragmentClass = Order_history.class;
break;
default:
fragmentClass = Main.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.flContent, fragment);
fragmentTransaction.commit();
// Highlight the selected item, update the title, and close the drawer
// menuItem.setChecked(true);
// setTitle(menuItem.getTitle());
drawerLayout.closeDrawers();
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
drawer_view.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/home"
android:title="Home"
/>
<item
android:id="#+id/orderhistory"
android:title="Cursos"
/>
</menu>
Order_history.java
public class Order_history extends Fragment {
public Order_history() {
// 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_order_history, container, false);
}
}
fragment_order_history.xml
<FrameLayout 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.enterprise.prueba.Order_history">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
Main.Java
public class Main extends Fragment {
public Main() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, null);
// Inflate the layout for this fragment
return rootView;
}
}
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="I'm a fragment"/>
</LinearLayout>
Edited
It's very weird, now I create a new project with the same code and this is the result when I select order history in Oncreate().
I Update my code to show you all the files

how to include items in navigation drawer

Here is MainActivity.java
public class MainActivity extends ActionBarActivity {
// inisiasi toolbar
private Toolbar toolbar;
// navigation drawer
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
String title = "My App";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
if (toolbar != null) {
toolbar.setTitle(title);
setSupportActionBar(toolbar);
}
initDrawer();
}
/**
* init navigation drawer thing
*/
private void initDrawer() {
//setup navigation drawer
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.txt_open, R.string.txt_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// when drawer closed
toolbar.setTitle(title);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// when drawer open
toolbar.setTitle("Nav menu");
}
};
// setDrawerlisterner
drawerLayout.setDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (drawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
and here is xml file layout view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- Toolbar -->
<include layout="#layout/toolbar" />
<!-- content -->
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:id="#+id/drawerLayout"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:background="#fff"
android:layout_height="match_parent">
<TextView
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:textColor="#000"
android:text="Our Content"
android:layout_height="wrap_content" />
</RelativeLayout>
<!-- nav drawer -->
<LinearLayout
android:layout_gravity="start"
android:orientation="vertical"
android:background="#fff"
android:layout_width="280dp"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:textColor="#000"
android:text="Nav drawer"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Does anyone know how to add a listview to navigation drawer. And i want to load a web page when user selects each item on navigation drawer into a fragment. I tried to implement a code from a sample but comes up with so many errors.
Well, there is nothing to afraid about NavigationDrawer. At first we may think that it is some special kind of activity and this and that. but it is so much simple.
Step 1 - Create xml file with 2 layouts
<FrameLayout>
//main screen contents
</FrameLayout>
<Linear/Relative/ListView/xyz>
// any layout that u want to be shown in navigation drawer
</Linear/Relative/ListView/xyz>
Step 2 - Define ur drawer in activity class with couple of codes
drawerLayout = (DrawerLayout) findViewById(R.id.NvDrawer);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close);
drawerLayout.setDrawerListener(drawerToggle);
and override this methods
#Override
public void onDrawerSlide(View view, float v) {
}
#Override
public void onDrawerOpened(View view) {
}
#Override
public void onDrawerClosed(View view) {
}
#Override
public void onDrawerStateChanged(int i) {
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
Step 3 - Add this code in onOptionsItemSelected
if (drawerToggle.onOptionsItemSelected(item)) {
return true;

Categories

Resources