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
}
}
};
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();
}
}
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
}
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 trying to use FAB with navigation drawer and fragment content that changes with onitemClcik() in navigation menu
but after I was clicked on any item and do replace() fragment I have get bank screen
class :
public class SubTaB extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener , ObservableScrollViewCallbacks {
#Bind(R.id.list_view)
ObservableListView mObservableListView;
#Bind(R.id.fabtoolbar)
FabToolbar mFabToolbar;
#Bind(R.id.fab)
android.support.design.widget.FloatingActionButton mFab;
#Bind(R.id.ic_call)
ImageView mIcCall;
#Bind(R.id.ic_email)
ImageView mIcEmail;
#Bind(R.id.ic_forum)
ImageView mIcForum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_ta_b);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ButterKnife.bind(this);
initListView();
mFabToolbar.setFab(mFab);
}
private void initListView() {
List<String> list = new ArrayList<String>(100);
for (int i = 0; i < 100; i++) {
list.add("Item " + i);
}
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, list);
// mObservableListView.setAdapter(adapter);
mObservableListView.setScrollViewCallbacks(this);
}
#Override
public void onScrollChanged(int i, boolean b, boolean b1) {
}
#Override
public void onDownMotionEvent() {
}
#Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
Log.d("","Scroll scroll scroll");
if (scrollState == ScrollState.UP) {
mFabToolbar.slideOutFab();
} else if (scrollState == ScrollState.DOWN) {
mFabToolbar.slideInFab();
}
}
#OnClick(R.id.fab)
void onFabClick() {
mFabToolbar.expandFab();
}
#OnClick(R.id.call)
void onClickCall() {
iconAnim(mIcCall);
}
#OnClick(R.id.ic_email)
void onClickEmail() {
iconAnim(mIcEmail);
}
#OnClick(R.id.ic_forum)
void onClickForum() {
iconAnim(mIcForum);
}
private void iconAnim(View icon) {
Animator iconAnim = ObjectAnimator.ofPropertyValuesHolder(
icon,
PropertyValuesHolder.ofFloat("scaleX", 1f, 1.5f, 1f),
PropertyValuesHolder.ofFloat("scaleY", 1f, 1.5f, 1f));
iconAnim.start();
}
///////////////////////////////////////
#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.sub_ta_b, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// mFabToolbar.slideOutFab();
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment newFragment= null;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//
if (id == R.id.nav_camera) {
newFragment = new OneFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, newFragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
newFragment = new DashDetails();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack("TAG");
transaction.commit();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
XML layot :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/fragment_container2"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/MyMaterialTheme.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/MyMaterialTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/fragment_container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
layout="#layout/FAB" />
</LinearLayout>
<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_sub_ta_b"
app:menu="#menu/activity_sub_ta_b_drawer" />
Your activity layout is a bit odd. You should have a root parent layout like for example CoordinatorLayout.
Your XML layout however does not have a root layout, the LinearLayouts are all siblings.
Another thing I noticed is that the LinearLayout around the FAB is the one you replace when replacing your fragment. This is wrong. Remove LinearLayout around the FAB and add a FrameLayout with id=fragment_container.
The layout structure could look like this
<CoordinatorLayout>
<AppBarLayout>
<Toolbar/>
//... other layouts here
</AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"/>
//... rest of your layout here
<FloatingActionButton android:gravity="bottom|end" />
</CoordinatorLayout>