I have used the NavigationDrawer Template in my application but the Functions of the Intent not working properly. I already implemented the navigation listener in class declaration but still the intent navigation not working. This is the place I got stuck at the first time. I have searched many sites but nothing happened in my application. Can you help me? I added some extra comments please dont consider it
public class MainActivity extends AppCompatActivity
implements ViewPager.OnPageChangeListener {
/**
* Extra to add the the launch intent to specify that user comes from the notification (used to
* show not the current month but the last one)
*/
public static final String FROM_NOTIFICATION_EXTRA = "fromNotif";
/**
* List of first date of each month available
*/
private List<Date> dates;
/**
* TextView that displays the name of the month
*/
private TextView monthTitleTv;
/**
* Button to go the previous month
*/
private Button previousMonthButton;
/**
* Button to go the next month
*/
private Button nextMonthButton;
/**
* ViewPager used to display each month in a Fragment
*/
private ViewPager pager;
/**
* The current {#link #pager} position
*/
private int selectedPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.monthly_report_progress_bar);
final View content = findViewById(R.id.monthly_report_content);
monthTitleTv = (TextView) findViewById(R.id.monthly_report_month_title_tv);
previousMonthButton = (Button) findViewById(R.id.monthly_report_previous_month_button);
nextMonthButton = (Button) findViewById(R.id.monthly_report_next_month_button);
pager = (ViewPager) findViewById(R.id.monthly_report_view_pager);
previousMonthButton.setText("<");
nextMonthButton.setText(">");
previousMonthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPosition > 0) {
selectPagerItem(selectedPosition - 1, true);
}
}
});
nextMonthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPosition < dates.size() - 1) {
selectPagerItem(selectedPosition + 1, true);
}
}
});
UIHelper.removeButtonBorder(previousMonthButton);
UIHelper.removeButtonBorder(nextMonthButton);
// Load list of monthly asynchronously since it can take time
new AsyncTask<Void, Void, List<Date>>() {
#Override
protected List<Date> doInBackground(Void... params) {
return DateHelper.getListOfMonthsAvailableForUser(MainActivity.this);
}
#Override
protected void onPostExecute(List<Date> dates) {
if (isFinishing()) {
return;
}
MainActivity.this.dates = dates;
configureViewPager();
progressBar.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
}
}.execute();
}
private void configureViewPager() {
pager.setOffscreenPageLimit(0);
pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
return new MonthlyReportFragment(dates.get(position));
}
#Override
public int getCount() {
return dates.size();
}
});
pager.addOnPageChangeListener((ViewPager.OnPageChangeListener) this);
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(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_camera:
Intent i = new Intent(MainActivity.this, Monthly_ExpenseEdit_activity.class);
startActivity(i);
break;
case R.id.nav_gallery:
Intent i1 = new Intent(MainActivity.this, ExpenseEditActivity.class);
startActivity(i1);
break;
}
return false;
}
});
}
/**
* Extra to add the the launch intent to specify that user comes from the notification (used to
* show not the current month but the last one)
*/
#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;
}
private void selectPagerItem(int position, boolean animate)
{
pager.setCurrentItem(position, animate);
onPageSelected(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
/**
* Extra to add the the launch intent to specify that user comes from the notification (used to
* show not the current month but the last one)
*/
#Override
public void onPageSelected(int position)
{
selectedPosition = position;
Date date = dates.get(position);
monthTitleTv.setText(DateHelper.getMonthTitle(this, date));
// Last and first available month
boolean last = position == dates.size() - 1;
boolean first = position == 0;
/**
* Extra to add the the launch intent to specify that user comes from the notification (used to
* show not the current month but the last one)
*/
nextMonthButton.setEnabled(!last);
nextMonthButton.setTextColor(ContextCompat.getColor(this, last ? R.color.monthly_report_disabled_month_button : android.R.color.white));
previousMonthButton.setEnabled(!first);
previousMonthButton.setTextColor(ContextCompat.getColor(this, first ? R.color.monthly_report_disabled_month_button : android.R.color.white));
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
XML:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_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"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
<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=".view.MonthlyReportActivity">
<ProgressBar android:id="#+id/monthly_report_progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:indeterminate="true" />
<LinearLayout android:id="#+id/monthly_report_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="47dp"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:gravity="center_vertical"
android:background="#color/primary_dark">
<Button
android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button android:id="#+id/monthly_report_previous_month_button"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:textSize="24dp"
android:background="#drawable/calendar_month_switcher_button_drawable" />
<TextView android:id="#+id/monthly_report_month_title_tv"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:textSize="21dp"
android:textColor="#android:color/white"
android:textAllCaps="true"
android:gravity="center" />
<Button android:id="#+id/monthly_report_next_month_button"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:textSize="24dp"
android:background="#drawable/calendar_month_switcher_button_drawable" />
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="#+id/monthly_report_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
in your onNavigationItemSelected() method return true instead of false
Also make sure the id exist in navigation drawer menu.
app:menu="#menu/menu_navigation"
use this code:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_camera:
Intent i = new Intent(MainActivity.this, Monthly_ExpenseEdit_activity.class);
startActivity(i);
break;
case R.id.nav_gallery:
Intent i1 = new Intent(MainActivity.this, ExpenseEditActivity.class);
startActivity(i1);
break;
}
return true; //change here
}
Related
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 have implemented a drawer layout whereby when I click a navigation view item a tab layout opens up. The tablayout comes in fine but the problem is when i click the back button of the tab layout the application crashes with No drawer view found with gravity LEFT. Also I have noticed that there is a bit of a lag when the navigation drawer closes when the tab layout comes in, the drawer does not close smoothly.
Below is my java code and xml:
public class Navigation extends AppCompatActivity implements
ItemFragment.OnHeadlineSelectedListener,
SortFragment.OnHeadlineSelectedListener{
private static final String TAG = Navigation.class.getSimpleName();
Toolbar toolbar;
FragmentManager mFragmentManager;
private TextView mCounter;
private ImageView cart;
FragmentTransaction mFragmentTransaction;
public int id, tabPosition = 0, tabPositionNavigation = 0;
private String drinkToSort = "empty";
SharedPreferences preferences;
private LocalStore localStore;
private String userName, email, location;
private String phone;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation);
localStore = new LocalStore(this);
id = localStore.getLoggedInUser().getId();
userName = localStore.getLoggedInUser().getUserName();
email = localStore.getLoggedInUser().getEmail();
phone = localStore.getLoggedInUser().getPhone();
Log.i(TAG,"USERDATA" + "[" + id + userName + email + phone + location + "]");
relativeLayout = (RelativeLayout) findViewById(R.id.main_content);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle("hello");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("hello");
}
};
Bundle extras = getIntent().getExtras();
if (extras != null) {
this.tabPosition = extras.getInt("tabPosition");
this.tabPositionNavigation = extras.getInt("tabPositionNavigation");
this.drinkToSort = extras.getString("drinkToSort");
Log.d(TAG, tabPosition + tabPositionNavigation + drinkToSort);
}
Bundle bundle = new Bundle();
bundle.putString("drinkToSort", drinkToSort);
LiquorFragment obj = new LiquorFragment();
obj.setArguments(bundle);
int width = getResources().getDisplayMetrics().widthPixels/2;
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new NavigationFragment()).commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.details_activity, menu);
RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.cart_no).getActionView();
mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
Log.d("sameSelectionCount", CartCounter.getCounter()+"");
mCounter.setText(""+CartCounter.getCounter());
cart = (ImageView) badgeLayout.findViewById(R.id.cart);
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("cart_no","cart_no");
Intent intent = new Intent(getApplicationContext(), ShoppingList.class);
startActivity(intent);
}
});
return true;
}
#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 void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onResume() {
super.onResume();
//TabFragment.viewPager.setCurrentItem(1);
Log.d("landposzq",tabPositionNavigation + "");
if (tabPositionNavigation != 0){
if (tabPositionNavigation == 1){
NavigationFragment.viewPager.setCurrentItem(0);
} else if (tabPositionNavigation == 2){
NavigationFragment.viewPager.setCurrentItem(1);
} else if (tabPositionNavigation == 3){
NavigationFragment.viewPager.setCurrentItem(2);
} else if (tabPositionNavigation == 4){
NavigationFragment.viewPager.setCurrentItem(3);
} else if (tabPositionNavigation == 5){
NavigationFragment.viewPager.setCurrentItem(4);
}
}
}
}
<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:background="#ffffff"
tools:openDrawer="start"
android:fitsSystemWindows="true">
<!--Main content-->
<RelativeLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/qb"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar" />
</RelativeLayout>
<!--Navigation Drawer-->
<android.support.design.widget.NavigationView
android:id="#+id/main_drawer"
android:layout_width="290dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="#color/white"
app:headerLayout="#layout/drawer_header"
app:itemTextColor="#000000"
app:itemIconTint="#color/qb"
app:menu="#menu/menu_drawer" >
<LinearLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginLeft="20dp"
android:src="#drawable/balloon4"
/>
<TextView
android:id="#+id/free_drinks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffff99"
android:gravity="center_vertical"
android:padding="10dp"
android:drawableRight="#drawable/direction"
android:height="60dp"
android:textSize="18sp"
android:text="GET FREE DRINKS"
android:textColor="#000000"
android:layout_gravity="bottom"
/>
</LinearLayout>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Change your onBackPressed() method as below :
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
In my app I have to use navigation drawer with all activities. So I have created a base activity called DrawerActivity. I wrote the code for navigation drawer in DrawerActivity and then extended the UserDashBoardActivity from DrawerActivity.
The problem is that DrawerActivity properties aren't executed in UserDashBoardActivity. I can't interact with DrawerActivity in UserDashBoardActivity. Here that drawer menu is in ActionBar in all the activities.
This is my DrawerActivity
public class DrawerActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_list_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerItems = getResources().getStringArray(R.array.navigation_drawer_items_array);
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(
this, R.layout.drawer_list_items, mDrawerItems));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout, R.drawable.ic_menu,
R.string.drawer_open, R.string.drawer_close) {
public void onDrawerOpened(View view) {
invalidateOptionsMenu();
}
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
for (int index = 0; index < menu.size(); index++) {
MenuItem menuItem = menu.getItem(index);
if (menuItem != null) {
// hide the menu items if the drawer is open
menuItem.setVisible(!drawerOpen);
}
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
switch (position) {
case 0: {
Intent intent = new Intent(DrawerActivity.this, UserDashBoardActivity.class);
startActivity(intent);
break;
}
case 1: {
Intent intent = new Intent(DrawerActivity.this, AdmissionActivity.class);
startActivity(intent);
break;
}
default:
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
This is my UseDashBoardActivity
public class UserDashBoardActivity extends DrawerActivity {
private Context context;
private ImageButton searchBtn;
private ImageButton favBtn;
private ImageButton profileBtn;
private ImageButton reminderBtn;
private ImageButton logoutBtn;
private ImageButton notificationBtn;
private ImageView seatchIcon;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
#Override
protected void onStart() {
super.onStart();
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onResume();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
AppActivityStatus.setActivityStoped();
}
#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_user_dash_boad, menu);
return true;
}
// delete the selected event from event list added here
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_notify:
return true;
case R.id.action_favourite:
return true;
case R.id.action_navigation:
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setCustomView(R.layout.action_bar_layout);
setContentView(R.layout.user_dash_board);
context = getApplicationContext();
searchBtn = (ImageButton) findViewById(R.id.search_btn);
favBtn = (ImageButton) findViewById(R.id.fav_btn);
profileBtn = (ImageButton) findViewById(R.id.profile_btn);
reminderBtn = (ImageButton) findViewById(R.id.reminder_btn);
notificationBtn = (ImageButton) findViewById(R.id.notification_btn);
logoutBtn = (ImageButton) findViewById((R.id.logout_btn));
final EditText Search = (EditText)findViewById(R.id.emailAddress);
mDrawerList = (ListView)findViewById(R.id.drawer_layout);
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent regAct = new Intent(getApplicationContext(), SearchActivity.class);
// Clears History of Activity
regAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(regAct);
}
});
favBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
Intent tabAct = new Intent(getApplicationContext(),TabHostActivity.class);
tabAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tabAct);
}
});
profileBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent tabAct = new Intent(getApplicationContext(),AboutCollegeActivity.class);
tabAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tabAct);
}
});
}
}
This is my actionbar xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:appmunu="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.after2.svirtzone.after2_gradle.UserDashBoardActivity">
<item
android:id="#+id/action_notify"
android:icon="#drawable/mail_icon"
appmunu:showAsAction="always"
android:title="Notification" />
<item
android:id="#+id/action_favourite"
android:icon="#drawable/favourite_icon"
appmunu:showAsAction="always"
android:title="Favourite" />
<item
//this is the menu button for navigation drawer
android:id ="#+id/action_navigation"
android:icon="#drawable/ic_menu"
appmunu:showAsAction = "always"
android:title="navigation"
android:layout_gravity="left"/>
</menu>
This is the xml layout for navigationdrawer listview
<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/activity_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" ></FrameLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
This layout is UserDashboard layout
?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:layout_gravity="center"
android:background="#color/appblue"
android:orientation="vertical">
<EditText
android:id="#+id/emailAddress"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:background="#drawable/edit_text_style"
android:gravity="center|start"
android:hint="#string/edittext_hint"
android:inputType="textEmailAddress"
android:maxLength="40"
android:textSize="18sp"
android:visibility="gone" />
<ImageView
android:id="#+id/search_icon_btn"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginLeft="580dp"
android:layout_marginRight="10dp"
android:layout_marginTop="-90dp"
android:padding="5dp"
android:src="#drawable/search_icon" />
<ImageButton
android:id="#+id/search_btn"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="5dp"
android:layout_marginRight="210dp"
android:layout_marginTop="30dp"
android:background="#drawable/search_blue"
android:gravity="center" />
<TextView
android:id="#+id/searchCollege"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginRight="100dp"
android:layout_marginTop="20dp"
android:text="#string/search_college"
android:textColor="#color/green"
android:textSize="30sp" />
<ImageButton
android:id="#+id/fav_btn"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="200dp"
android:layout_marginRight="5dp"
android:layout_marginTop="-305dp"
android:background="#drawable/fav_blue"
android:gravity="center" />
<TextView
android:id="#+id/myFavourites"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="500dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:text="#string/my_favourites"
android:textColor="#color/green"
android:textSize="30sp" />
</LinearLayout>
The UserDashboard activity is executed as it is but I need the property of DrawerActivity to be executed along with this activity. How to do it?
Let the parent Activity add the required ViewGroup as child of the FrameLayout. To achieve this, use the following method for DrawerActivity:
protected void addToContentView(int layoutResID)
{
// as part of onCreate() we had already
// setContentView(R.layout.activity_drawer);
if (layoutResID >= 0)
{
Toast.makeText(this, "activity content found", Toast.LENGTH_LONG).show();
FrameLayout fl = (FrameLayout)findViewById(R.id.activity_frame);
View.inflate(this, layoutResID, fl);
}
else
{
Toast.makeText(this, "activity content missing", Toast.LENGTH_LONG).show();
}
}
Then, in the onCreate() method of the child Activity:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// call this instead of setContentView()
addToContentView(R.layout.activity_user_dashboard);
// put here your code as before...
}
Drawer's 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"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<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/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
/>
<!--you need to add everything to this frameLayout then only you will be able to access Navigation DrawerLayout-->
<FrameLayout
android:id="#+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</LinearLayout>
<ListView
android:id="#+id/navigation_list"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:fitsSystemWindows="true"
android:background="#color/white"
/>
</android.support.v4.widget.DrawerLayout>
The Activity with Drawer:(Only important code is shown)
public abstract class BaseDrawerLayoutActivity extends AppCompatActivity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_drawer_layout_activity);
//rest of the things
//NOTE: loadNavMenu is abstract so that you can implement it in other activities as per you need, otherwise remove this and load it here itself
loadNavMenu();
}
protected abstract void loadNavMenu();
// call this method whenever you enter new activity and load the fragment here.
public void showFragment(Fragment object, String title) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, object);
transaction.commit();
}}
Those activities which need the drawer menu can inherit above class. Not inflate all the layout's inside FrameLayout only.
public class MainActivity extends BaseDrawerLayoutActivity {
public static final String TAG = OLMSActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//the method below will call the BaseDrawerLayoutActivity method and change the fragment for you to see.
showFragment(new MyProfileFragment(), "My Profile");
}
#Override
protected void loadNavMenu() {
NavItems.clear();
//load your menu items
}
private void loadNavFavourites(){
//todo
}}
MyProfileFragment is just a class with fragment and this one call inflate a layout in its OnCreateView method.
I'm having a few issues with my NavigationDrawerwhich I want to run from and Activitywhich contains 2 fragments. The idea is that the main fragment will be changed by selecting from the NavigationDrawer
I'm getting the following error when running:
Process: XXXX, PID: 31040
java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams cannot be cast to android.support.v4.widget.DrawerLayout$LayoutParams
at android.support.v4.widget.DrawerLayout.isDrawerView(DrawerLayout.java:1129)
at android.support.v4.widget.DrawerLayout.isDrawerOpen(DrawerLayout.java:1379)
at XXXX.NavigationDrawerFragment.isDrawerOpen(NavigationDrawerFragment.java:117)
at XXXX.EditFactFind.onCreateOptionsMenu(EditFactFind.java:192)
at android.app.Activity.onCreatePanelMenu(Activity.java:2846)
at com.android.internal.policy.PhoneWindow.preparePanel(PhoneWindow.java:567)
at com.android.internal.policy.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:939)
at com.android.internal.policy.PhoneWindow$1.run(PhoneWindow.java:271)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
My activity that contains the fragments XML is:
<?xml version="1.0" encoding="utf-8"?>
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="XXXX.MainActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:id="#+id/fragment_container"
android:layout_alignParentBottom="true">
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment
android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="XXXX.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/editFactFindTop"
android:name="XXXX.editFactFind_top"
tools:layout="#layout/fragment_edit_fact_find_top"/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3"
android:id="#+id/fragment_editFactFind"
android:name="XXXX.secA_pg1"
tools:layout="#layout/fragment_sec_a_pg1" />
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
My NavigationDrawer XML is:
<ListView 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"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#cccc"
tools:context=".NavigationDrawerFragment" />
My Top fragment XML is:
<android.support.v4.widget.DrawerLayout 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="XXXX.editFactFind_top">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:id="#+id/fragment_container"
android:layout_alignParentBottom="true">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/titleEditText"
android:id="#+id/titleViewText" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/titleViewText"
android:layout_alignBaseline="#id/titleViewText"
android:id="#+id/titleEditText"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/titleEditText"
android:layout_alignBaseline="#id/titleViewText"
android:layout_alignParentRight="true"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_marginLeft="20dp"
android:text="#string/dateTextView"
android:id="#id/dateTextView"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/saveButton"
android:id="#id/saveButton"
android:layout_below="#id/titleEditText"
android:layout_marginTop="50dp"
android:visibility="visible" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cancelButton"
android:layout_marginLeft="10dp"
android:id="#id/cancelButton"
android:layout_toRightOf="#id/saveButton"
android:layout_alignBaseline="#id/saveButton"
android:visibility="visible" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:id="#+id/nextButton"
android:layout_alignBaseline="#id/cancelButton"
android:layout_toRightOf="#id/cancelButton"/>
</RelativeLayout>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
My main fragment XML is:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="XXXX.secA_pg1">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:text="#string/Sec_A_pg1_fragment"
android:id="#+id/Sec_A_pg1_fragment"
android:layout_below="#id/nextButton"/>
</RelativeLayout>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
My editFactFind java is:
public class EditFactFind extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks {
public static final int RESULT_DELETE = -500;
private boolean isInEditMode = true;
private boolean isAddingFactFind = true;
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_factfind);
final Button saveButton = (Button)findViewById(R.id.saveButton);
final Button cancelButton = (Button)findViewById(R.id.cancelButton);
final EditText titleEditText = (EditText)findViewById(R.id.titleEditText);
//final EditText factFindEditText = (EditText)findViewById(R.id.factFindEditText);
final TextView dateTextView = (TextView)findViewById(R.id.dateTextView);
final Button nextButton =(Button) findViewById(R.id.nextButton);
//Create fragment and give it an argument for the selected article
secA_pg1 iniSecFrag = new secA_pg1();
Bundle args = new Bundle();
args.putInt(secA_pg1.ARG_INDEX, 1);
iniSecFrag.setArguments(args);
FragmentTransaction initialTransaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
//initialTransaction.replace(R.id.fragment_container, iniSecFrag);
// initialTransaction.addToBackStack(null);
// Fragment iniSecFrag = new secA_pg1();
initialTransaction.add(R.id.fragment_container, iniSecFrag);
//Commit the transaction
initialTransaction.commit();
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer); // Activity_nav_drawer.xml
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
Serializable extra = getIntent().getSerializableExtra("FactFind");
if(extra != null)
{
FactFind factFind = (FactFind) extra;
titleEditText.setText(factFind.getTitle());
// factFindEditText.setText(factFind.getFactFindTitle());
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String date = dateFormat.format(factFind.getDate());
dateTextView.setText(date);
isInEditMode = false;
titleEditText.setEnabled(false);
// factFindEditText.setEnabled(false);
saveButton.setText("Edit");
isAddingFactFind = false;
}
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setResult(RESULT_CANCELED, new Intent());
finish();
}
});
nextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//secA_pg1 secFrag = (secA_pg1) getFragmentManager().findFragmentById(R.id.Sec_A_pg1_fragment);
//Create fragment and give it an argument for the selected article
secA_pg2 newSecFrag = new secA_pg2();
Bundle args = new Bundle();
args.putInt(secA_pg2.ARG_INDEX, 2);
newSecFrag.setArguments(args);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_editFactFind, newSecFrag);
transaction.addToBackStack(null);
//Commit the transaction
transaction.commit();
}
});
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(isInEditMode)
{
Intent returnIntent = new Intent();
FactFind factFind = new FactFind(titleEditText.getText().toString(),Calendar.getInstance().getTime());
returnIntent.putExtra("FactFind", factFind);
setResult(RESULT_OK, returnIntent);
finish();
}
else
{
isInEditMode = true;
saveButton.setText("Save");
titleEditText.setEnabled(true);
// factFindEditText.setEnabled(true);
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.are_you_sure_you_want_to_delete_this_fact_find_it_can_t_be_undone_);
builder.setTitle("Confirm Delete");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent returnIntent = new Intent();
setResult(RESULT_DELETE, returnIntent);
finish();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.nav_drawer, menu);
restoreActionBar();
return true;
}
else {
//return super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.action_menu, menu);
return true;
}
}
//#Override
public void onSelectedFragChanged(int index) {
FragmentManager fragmentManager = getFragmentManager();
secA_pg1 secA_pg1 = (secA_pg1) fragmentManager.findFragmentById(R.id.Sec_A_pg1_fragment);
secA_pg1.setSectionTitle(index);
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
//actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
}
}
and finally my NavigationDrawerFragment java is
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
"Assets",
"ID",
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
// mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
// R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
// getActivity().InvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
// getActivity().InvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
// showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
//actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((Activity) getActivity()).getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
I've attempted several things and from research and the error I believe one of my XML files is incorrectly laid out and it sees it as a Frame Layout instead of a drawer but I can't figure out exactly where. I've tried amending the layouts in many ways but have had no luck.
Thanks :)
It looks like there's a few things wrong here, unless I'm missing something more complex that you're trying to achieve.
First, when you're using this DrawerLayout, it should have the content and the drawer in separate sections, whereas here everything is grouped under one FrameLayout. The basic structure of the XML would be something like:
<android.support.v4.widget.DrawerLayout>
<FrameLayout>
your main content stuff here
</FrameLayout>
<FrameLayout>
navigationdrawer stuff here
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
They don't have to both be FrameLayouts, but the important thing is that there are two child views and they are in that order. Have a look at the guidance here.
The other main structural thing is that you don't need a DrawerLayout in all of your Fragments as well. The DrawerLayout belongs to the Activity, each fragment can just show its contents.
I believe that your problem is that the FrameLayout content's elements shouldn't contain any other views in your layouts.
For example, in your main fragment, your layout should look like this:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="XXXX.secA_pg1">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:text="#string/Sec_A_pg1_fragment"
android:id="#+id/Sec_A_pg1_fragment"
android:layout_below="#id/nextButton"/>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
And keep in mind that when calling the isDrawerOpen(View drawer) method, you should pass as the parameter the RelativeLayout (in this example), that's actually the drawer view and also that this view must specify its horizontal gravity with the android:layout_gravity attribute.
I base my answer in the official documentation of DrawerLayout:
https://developer.android.com/training/implementing-navigation/nav-drawer.html
I followed the android guideline and completed a layout looks like this:
<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"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id= "#+id/my_awesome_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/fragmentContainer"/>
</LinearLayout>
<LinearLayout
android:id="#+id/left_drawer_view"
android:layout_width="250dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="start">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/wall"
android:layout_margin="0dp"
android:padding="0dp"
android:scaleType="center"
/>
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/placeholder"
android:layout_margin="16dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IGuessI'mUsername?"
android:textColor="#fff"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_margin="10dp"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:orientation="vertical"
android:background="#fff"
android:id="#+id/left_drawer_item"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/side_item_home"
android:text="Home"
android:drawablePadding="5dp"
android:padding="5dp"
android:gravity="center_vertical"
android:drawableLeft="#drawable/ic_menu_home"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Activities"
android:drawablePadding="5dp"
android:id="#+id/side_item_activities"
android:padding="5dp"
android:gravity="center_vertical"
android:drawableLeft="#drawable/ic_menu_search_holo_light"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Settings"
android:drawablePadding="5dp"
android:id="#+id/side_item_settings"
android:padding="5dp"
android:gravity="center_vertical"
android:drawableLeft="#drawable/ic_action_settings"
/>
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
FYI, I did not use Android.R.Id, but my own R.id.fragmentContainer to load the fragments. But apparently, the drawer layout is under the fragment loaded in the FrameLayout. If I click the item on the DrawerLayout, the fragments receive the gesture, not the DrawerLayout, although it still display correctly.
I need your two cents, guys. All answers and comments are appreciated.
Edit:
Here is the requested code.
public class ClipMe_main extends ActionBarActivity implements View.OnClickListener {
private HashMap<String, Stack<Fragment>> mStacks;
SlidingTabFragment homeFragment;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private String[] mTitle;
Fragment settingsFragment;
private ArrayList<DrawerItemModel> drawerData;
android.support.v7.app.ActionBar bar;
ActionBarDrawerToggle mDrawerToggle;
SlidingTabLayout mSlidingTabLayout;
public static DisplayMetrics displayMetrics;
FragmentManager fm;
FragmentPagerAdapter adapterViewPager;
int visiblePage;
TextView sideBarHome;
TextView sideBarActivities;
TextView sideBarSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main_activity);
displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(displayMetrics);
registerReceiver(receiverDownloadComplete, new IntentFilter(DownloadService.ACTION_DOWNLOAD_COMPLETE));
sideBarHome = (TextView) findViewById(R.id.side_item_home);
sideBarActivities = (TextView) findViewById(R.id.side_item_activities);
sideBarSettings = (TextView) findViewById(R.id.side_item_settings);
sideBarSettings.setOnClickListener(this);
sideBarHome.setOnClickListener(this);
sideBarActivities.setOnClickListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
new Toolbar(ClipMe_main.this),
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(getTitle());
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(getTitle());
}
};
setUpView();
setUpHomeFragment();
setUpSettingFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbar.setBackgroundColor(getResources().getColor(R.color.swipe_refresh_2));
setSupportActionBar(toolbar);
mDrawerLayout.setDrawerListener(mDrawerToggle);
bar = this.getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
bar.setDisplayShowTitleEnabled(true);
}
private void setUpSettingFragment() {
settingsFragment = new SettingsFragment();
}
void setUpView() {
setContentView(R.layout.layout_main_activity);
}
void setUpHomeFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
homeFragment = new SlidingTabFragment();
transaction.add(R.id.fragmentContainer, homeFragment, "home");
transaction.commit();
}
public void pushFragments(String tag, Fragment fragment, boolean shouldAnimate) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (shouldAnimate)
ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
ft.replace(R.id.fragmentContainer, fragment, tag).addToBackStack(null);
ft.commit();
Log.d("FragmentManager", "Push " + tag);
}
public void getFragmentAndUpdate(int page) {
PopularFragment currentFragment = homeFragment.getCurrentFragment();
currentFragment.requestMoreData(page);
Log.d("FragmentPage", String.valueOf(page));
}
#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);
mDrawerToggle.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_clipme_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.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int id = item.getItemId();
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public int findVisibleFragment(){
Fragment homeFragment = (Fragment) getSupportFragmentManager().findFragmentByTag("home");
Fragment activitiesFragment = (Fragment) getSupportFragmentManager().findFragmentByTag("activities");
Fragment settingsFragment = (Fragment) getSupportFragmentManager().findFragmentByTag("settings");
Fragment likeFragment = (Fragment) getSupportFragmentManager().findFragmentByTag("like");
Fragment commentFragment = (Fragment) getSupportFragmentManager().findFragmentByTag("comment");
if(homeFragment!= null && homeFragment.isVisible()){
return 1;
} else if(activitiesFragment!= null && activitiesFragment.isVisible()){
return 2;
} else if (settingsFragment!= null && settingsFragment.isVisible()){
return 3;
} else if (likeFragment!= null && likeFragment.isVisible()){
return 4;
} else if (commentFragment!= null && commentFragment.isVisible()){
return 5;
} else
return 0;
}
#Override
public void onClick(View v) {
if (v == sideBarHome){
if (findVisibleFragment() == 1){
mDrawerLayout.closeDrawers();
} else {
mDrawerLayout.closeDrawers();
pushFragments("activities", homeFragment, true);
}
}
if (v == sideBarActivities){
if (findVisibleFragment() == 2){
mDrawerLayout.closeDrawers();
} else {
mDrawerLayout.closeDrawers();
pushFragments("activities", new ActivitiesFragment(), true);
}
}
if (v == sideBarSettings){
if (findVisibleFragment() == 1){
mDrawerLayout.closeDrawers();
} else {
mDrawerLayout.closeDrawers();
pushFragments("activities", settingsFragment, true);
}
}
}
}
The issue i found is in the onClick() method. Try changing the function as below
public Fragment findVisibleFragment() {
FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.fragmentContainer);
return fragment;
}
Edit:
set the same listener to multiple views.
sideBarHome.setOnClickListener(clickListener);
sideBarSettings.setOnClickListener(clickListener);
Refer this clicklistener object to the view and you can use the same logic to differentiate views
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view.getId() == R.id.side_item_home) {
// mDrawerLayout.closeDrawers();
if (!(findVisibleFragment() instanceof SlidingTabFragment)) {
pushFragments("activities", homeFragment, true);
}
}
else if() {
//rest click logic
}
}
};