I am using a navigation drawer that fetches the album list from picasa web api. I have been trying to implement that same list as the tab items. Can someone please help me with implementing it?
This is the Navigation Drawer item class to show the albums in the navigation drawer.
public class NavDrawerItem {
private String albumId, albumTitle;
// boolean flag to check for recent album
private boolean isRecentAlbum = false;
public NavDrawerItem() {
}
public NavDrawerItem(String albumId, String albumTitle) {
this.albumId = albumId;
this.albumTitle = albumTitle;
}
public NavDrawerItem(String albumId, String albumTitle,
boolean isRecentAlbum) {
this.albumTitle = albumTitle;
this.isRecentAlbum = isRecentAlbum;
}
public String getAlbumId() {
return albumId;
}
public void setAlbumId(String albumId) {
this.albumId = albumId;
}
public String getTitle() {
return this.albumTitle;
}
public void setTitle(String title) {
this.albumTitle = title;
}
public boolean isRecentAlbum() {
return isRecentAlbum;
}
public void setRecentAlbum(boolean isRecentAlbum) {
this.isRecentAlbum = isRecentAlbum;
}
}
Nav drawer list adapter
package com.techsprint.wallpaperpro.helper;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.techsprint.wallpaperpro.NavDrawerItem;
import com.techsprint.wallpaperpro.R;
import java.util.ArrayList;
/**
* Created by Mahe on 6/18/2015.
*/
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context,
ArrayList<NavDrawerItem> navDrawerItems) {
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#Override
public int getCount() {
return navDrawerItems.size();
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}
The activity main layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="true">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="#dimen/list_view_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/list_background"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="#dimen/list_view_divider_height"
android:listSelector="#drawable/list_selector" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Drawer item 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="#dimen/drawer_list_item_layout_height"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="#dimen/drawer_list_item_layout_height"
android:background="#drawable/list_selector">
<ImageView
android:id="#+id/navimage_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_subject_black_24dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/navimage_list"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="#dimen/drawer_list_item_padding"
android:paddingRight="#dimen/drawer_list_item_padding"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#color/list_item_title" />
</RelativeLayout>
</LinearLayout>
And my main activity
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// Navigation drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private List<Category> albumsList;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private Toolbar toolbar;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// Getting the albums from shared preferences
albumsList = AppController.getInstance().getPrefManger().getCategories();
// Insert "Recently Added" in navigation drawer first position
Category recentAlbum = new Category(null,
getString(R.string.nav_drawer_recently_added));
albumsList.add(0, recentAlbum);
// Loop through albums in add them to navigation drawer adapter
for (Category a : albumsList) {
navDrawerItems.add(new NavDrawerItem(a.getId(), a.getTitle()));
}
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// Setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// Enabling action bar app icon and behaving it as toggle button
/*getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(
android.R.color.transparent)));*/
getSupportActionBar().setDisplayShowHomeEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
String deviceName = android.os.Build.MODEL;
String deviceMan = android.os.Build.MANUFACTURER;
String HARDWARE = Build.HARDWARE;
String TYPE = Build.TYPE;
String board = Build.BOARD;
/**
* Navigation drawer menu item click listener
*/
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
/**
* On menu item selected
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
/* if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}*/
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
// Selected settings menu item
// launch Settings activity
Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(intent);
return true;
case R.id.googleplus:
Intent intent1 = new Intent(MainActivity.this, GooglePlusActivity.class);
startActivity(intent1);
return true;
case R.id.feedback:
final Intent _Intent = new Intent(android.content.Intent.ACTION_SEND);
_Intent.setType("text/html");
_Intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{getString(R.string.mail_feedback_email)});
_Intent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.mail_feedback_subject));
_Intent.putExtra(android.content.Intent.EXTRA_TEXT, "Please Leave Your Valuable Feedback Above This Line" + "\n" + deviceMan + " " + deviceName + "," + " " + HARDWARE + "," + " " + board + "," + " " + TYPE);
startActivity(Intent.createChooser(_Intent, getString(R.string.title_send_feedback)));
return true;
case R.id.followus:
Intent intent2 = new Intent(MainActivity.this, FollowUsActivity.class);
startActivity(intent2);
return true;
case R.id.test:
Intent intent3 = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent3);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
// Recently added item selected
// don't pass album id to grid fragment
fragment = GridFragment.newInstance(null);
break;
default:
// selected wallpaper category
// send album id to grid fragment to list all the wallpapers
String albumId = albumsList.get(position).getId();
fragment = GridFragment.newInstance(albumId);
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(albumsList.get(position).getTitle());
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e(TAG, "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
//getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
The application is a wallpaper app which fetches data from the picasa web api. The app uses the volley library.
Related
I know this question might have been asked so much but out of all those answers I've went through, non didn't work for me. I get this exception when I intent from an activity to a fragment inflated to a NavigationDrawer Activity:
java.lang.IllegalArgumentException: No view found for id 0x7f0800c6 (xyz.ummo.user:id/frame) for fragment MyProfileFragment{16c76dd4 (91011ab5-3b76-4ccb-8573-f2b49ba96f08) id=0x7f0800c6 }
I've tried almost all approaches of switching screens from an activity to a fragment inflated into a NavigationDrawerActivity. Please go through the following java code and xml layout as sub-headed:
Method I used to intent from Activity to Fragment:
public void finishEditProfile(View view){
MyProfileFragment fragment = MyProfileFragment.newInstance("param1", "param2");
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.frame, fragment , "");
transaction.addToBackStack(null);
transaction.commit();
}
MyProfileFragment.java which is the Fragment class:
public class MyProfileFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
TextView thisOneNayo;
public MyProfileFragment() {
// Required empty public constructor
}
public static MyProfileFragment newInstance(String param1, String param2) {
MyProfileFragment fragment = new MyProfileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_my_profile, container, false);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
MainScreen.java class which is the container class:
public class MainScreen extends AppCompatActivity
implements MyProfileFragment.OnFragmentInteractionListener,
NavigationView.OnNavigationItemSelectedListener{
private Fragment fragment;
private DrawerLayout drawer;
private NavigationView navigationView;
private Toolbar toolbar;
private ImageView messageIconButton;
private ProgressBar circularProgreesBarButton;
// tags used to attach the fragments
private static final String TAG_HOME = "home";
private static final String TAG_PROFILE = "profile";
private static final String TAG_PAYMENTS = "paymentMethods";
private static final String TAG_SERVICE_HISTORY = "serviceHistory";
private static final String TAG_LEGAL_TERMS = "legalTerms";
public static String CURRENT_TAG = TAG_HOME;
private boolean anyServiceInProgress = false;
private int serviceProgress = 0;
// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
// index to identify current nav menu item
public static int navItemIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Ummo");
//initialise the toolbar icons message icon and circular progress bar icon
messageIconButton = findViewById(R.id.message_icon_button);
circularProgreesBarButton = findViewById(R.id.circular_progressbar_btn);
circularProgreesBarButton.setProgress(serviceProgress);
mHandler = new Handler();
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_home) {
} else if (id == R.id.nav_profile) {
} else if (id == R.id.nav_payment_methods) {
} else if (id == R.id.nav_service_history) {
}
else if (id == R.id.nav_legal_terms) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri){
//you can leave it empty
}
private void loadHomeFragment() {
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// home
setTitle("Ummo");
messageIconButton.setVisibility(View.VISIBLE);
circularProgreesBarButton.setVisibility(View.VISIBLE);
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// My Profile
MyProfileFragment myProfileFragment = new MyProfileFragment();
messageIconButton.setVisibility(View.GONE);
circularProgreesBarButton.setVisibility(View.GONE);
setTitle("Profile");
return myProfileFragment;
case 2:
// payment methods fragment
PaymentMethodsFragment paymentMethodsFragment = new PaymentMethodsFragment();
messageIconButton.setVisibility(View.GONE);
circularProgreesBarButton.setVisibility(View.GONE);
setTitle("Payment Method");
return paymentMethodsFragment;
case 3:
// service history fragment
ServiceHistoryFragment serviceHistoryFragment = new ServiceHistoryFragment();
return serviceHistoryFragment;
case 4:
// legal terms fragment
LegalTermsFragment legalTermsFragment= new LegalTermsFragment();
return legalTermsFragment;
default:
return new HomeFragment();
}
}
private void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_profile:
navItemIndex = 1;
CURRENT_TAG = TAG_PROFILE;
break;
case R.id.nav_payment_methods:
navItemIndex = 2;
CURRENT_TAG = TAG_PAYMENTS;
break;
case R.id.nav_service_history:
navItemIndex = 3;
CURRENT_TAG = TAG_SERVICE_HISTORY;
break;
case R.id.nav_legal_terms:
navItemIndex = 4;
CURRENT_TAG = TAG_LEGAL_TERMS;
break;
default:
navItemIndex = 0;
}
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
public void setAnyServiceInProgress(boolean anyServiceInProgress) {
this.anyServiceInProgress = anyServiceInProgress;
}
public void setServiceProgress(int serviceProgress) {
this.serviceProgress = serviceProgress;
}
public void goToEditProfile(View view){
TextView textViewToEdit;
String textToEdit = " ", toolBarTitle = " ";
switch(view.getId()){
case R.id.full_name:
textViewToEdit = view.findViewById(view.getId());
textToEdit = textViewToEdit.getText().toString();
toolBarTitle = "Enter your full name";
break;
case R.id.id_number:
textViewToEdit = view.findViewById(view.getId());
textToEdit = textViewToEdit.getText().toString();
toolBarTitle = "Enter your ID Number";
break;
case R.id.contact:
textViewToEdit = view.findViewById(view.getId());
textToEdit = textViewToEdit.getText().toString();
toolBarTitle = "Enter your phone number";
break;
case R.id.email:
textViewToEdit = view.findViewById(view.getId());
textToEdit = textViewToEdit.getText().toString();
toolBarTitle = "Enter your email";
break;
}
MyProfileFragment myProfileFragment = new MyProfileFragment();
Intent intent= new Intent(this, EditMyProfile.class);
String tag = myProfileFragment.getTag();
intent.putExtra(EditMyProfile.CONST_TAG, tag);
intent.putExtra("name", textToEdit);
intent.putExtra("toolBarTitle", toolBarTitle);
startActivity(intent);
}
public void finishEditrofile(View view){
Fragment fragment = new MyProfileFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, fragment, "TAG_PROFILE");
transaction.addToBackStack(null);
transaction.commit();
}
}
activity_main_screen.xml which is the layout of the fragment i want to move to:
<androidx.drawerlayout.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_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:theme="#style/NavigationDrawerStyle"
app:headerLayout="#layout/nav_header_main_screen"
app:menu="#menu/activity_main_screen_drawer" />
app_bar_main_screen.xml which is part of the activity_main_screen.xml and contains the container for the fragments:
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main"
tools:context=".MainScreen">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:id="#+id/message_icon_button"
android:src="#drawable/message_toolbar_icon"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
/>
<ProgressBar
android:id="#+id/circular_progressbar_btn"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="50dp"
android:layout_height="50dp"
android:indeterminate="false"
android:max="100"
android:progress="50"
android:layout_gravity="right"
android:progressDrawable="#drawable/circular_progress_bar"
android:secondaryProgress="100"
/>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</FrameLayout>
Disclaimer: This is the first app I am building so I am learning the hard way to use fragments first, so my code is all over the place.
I have menu items inside a navigation view that loads fine however the menu item clicks don't work. It doesn't crash it just stares at me. I would like to use an intent to display a fragment and I am lost from changing and trying so many different options.
XML FOR NAV DRAWER & MENU ITEMS:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_pageone"
android:background="#drawable/rygg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbarThumbVertical="#color/primary_dark_color"
tools:openDrawer="start"
tools:context="com.android.nohiccupsbeta.pageone">
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.design.widget.NavigationView
android:id="#+id/navigation_header_container"
app:headerLayout="#layout/header"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:itemIconTint="#color/category_vodka"
app:itemTextColor="#color/primary_dark_color"
app:menu="#menu/drawermenu"
android:layout_gravity="start" >
</android.support.design.widget.NavigationView>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
JAVA:
public class pageone extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pageone);
setupDrawer();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drawermenu, menu);
return true;
}
/**
*
* #param item For the hamburger button
* #return
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
switch (item.getItemId()) {
case R.id.itemWhiskey:
Intent whiskeyIntent = new Intent(pageone.this, whiskeyActivity.class);
startActivity(whiskeyIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Make sure the drawer open and closes in sync with UI visual
* #param savedInstanceState
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mToggle.syncState();
}
/**
* Function to make sure all the drawer open & closes properly
*/
public void setupDrawer() {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_pageone);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_closed) {
#Override
public void onDrawerClosed(View closeView) {
Toast.makeText(pageone.this, "Happy You Learned", Toast.LENGTH_SHORT).show();
super.onDrawerClosed(closeView);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View openView) {
Toast.makeText(pageone.this, "Effects Of Alcohol", Toast.LENGTH_SHORT).show();
super.onDrawerOpened(openView);
invalidateOptionsMenu();
}
};
mDrawerLayout.addDrawerListener(mToggle);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
MenuItem itemWhiskey = (MenuItem) findViewById(R.id.itemWhiskey);
itemWhiskey.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem itemWhiskey) {
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
return true;
}
});
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
XML FOR FRAGMENT:
<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"
android:orientation="vertical"
android:id="#+id/frame_container2"
tools:context="com.android.nohiccupsbeta.WhiskeyFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/frag_whiskey_skin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="8dp"
android:textColor="#000000"
android:textSize="16sp" />
<ImageButton
android:id="#+id/expand_collapse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:background="#android:color/transparent"
android:src="#drawable/ic_expand_more"
android:padding="16dp"/>
</FrameLayout>
JAVA:
public class WhiskeyFragment extends Fragment {
private TextView mWhiskeySkin;
#Override
public void onViewCreated(View view, #Nullable Bundle SavedInstanceState) {
super.onViewCreated(view, SavedInstanceState);
getActivity().setTitle("WHISKEY EFFECTS");
mWhiskeySkin = (TextView) view.findViewById(R.id.frag_whiskey_skin);
mWhiskeySkin.setText(R.string.whiskey_skin);
hasOptionsMenu();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_whiskey, container, false);
hasOptionsMenu();
return v;
}
}
XML FOR SECOND ACTIVITY:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
JAVA:
public class whiskeyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whiskey);
}
public class Whiskeyed {
private String whiskeySkin;
private String whiskeyBrain;
public String getWhiskeySkin(){
return whiskeySkin;
}
public String getWhikeyBrain(){
return whiskeyBrain;
}
public void setWhiskeySkin(String whiskey_skin){
this.whiskeySkin = whiskey_skin;
}
public void setWhiskeyBrain(String whiskeyBrain) {
this.whiskeyBrain = whiskeyBrain;
}
}
}
try to change to content of your onNavigationItemSelected of your pageone.java
from here:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
MenuItem itemWhiskey = (MenuItem) findViewById(R.id.itemWhiskey);
itemWhiskey.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem itemWhiskey) {
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
return true;
}
});
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
to here:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_pageone); // ID of your drawerLayout
int id = item.getItemId();
switch (id) {
case R.id.menu1: // Change this as your menuitem in menu.xml.
// Your fragment code goes here..
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
break;
case R.id.menu2: // Change this as your menuitem in menu.xml.
// or Your fragment code goes here...
break;
}
mDrawerLayout.closeDrawer(GravityCompat.START, true);
return true;
}
I am working on an Android project in which I am using drawer for showing some always used activities. I have made sure that the activities dont need any special data, and can be started once logged in. But I dont know how to include the drawer in all XML files where I have my activities. I cannot find any good reference.
Also, When I do that, how can i start the activity instead of using fragments. So, for example, below is an example of my RestaurantLists xml file and displaying users xml file, where and how can I include the drawer there. Thanks.
Sorry for the long code, I am using somewhere ListActivity, somewhere just Activity, then baseadapter, I want to add drawer in all. Thats why. Thank you.
restos.xml
<?xml version="1.0" encoding="UTF-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
displayUserList.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:id="#+id/usersdisplaylist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
>
</ListView>
</RelativeLayout>
I am using an adapter for displaying users, here is the adapter code and subsequent xml. Please note, my question remains the same, how to include drawer in all XML files, so it is displayed.
public class UserAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public UserAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null)
view = inflater.inflate(R.layout.userprofiles, null);
TextView username = (TextView) view.findViewById(R.id.userName);
ImageView userImage = (ImageView) view.findViewById(R.id.userImage);
HashMap<String, String> usersList = new HashMap<>();
usersList = data.get(position);
username.setText(usersList.get(OtherUsers.firstName));
byte [] encodeByte=usersList.get(OtherUsers.userImage).getBytes();
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
userImage.setImageBitmap(bitmap);
return view;
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants"
android:padding="5dip" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:orientation="vertical"
>
<ImageView
android:id="#+id/userImage"
android:layout_width="140dp"
android:layout_height="200dp"
android:scaleType="fitXY"
android:padding="5dp"
android:layout_weight="1"
android:contentDescription="userPhoto" />
<TextView
android:id="#+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:gravity="center"
android:layout_gravity="center_horizontal|top"
android:ellipsize="end"
android:scrollHorizontally="true"
android:layout_marginTop="10dp"
/>
</LinearLayout>
</RelativeLayout>
As you can see in the code below, i have commented out the code where I must start fragments. Shall I just start an Intent there, and then close the drawer?
Here is my code for displayView :
public class DrawerLoader extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<DrawerModel> navDrawerItems;
private DrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawerlayout);
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<DrawerModel>();
navDrawerItems.add(new DrawerModel(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new DrawerModel(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new DrawerModel(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new DrawerModel(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new DrawerModel(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new DrawerModel(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new DrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
// fragment = new HomeFragment();
break;
case 1:
// fragment = new FindPeopleFragment();
break;
case 2:
// fragment = new PhotosFragment();
break;
case 3:
// fragment = new CommunityFragment();
break;
case 4:
// fragment = new PagesFragment();
break;
case 5:
// fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
// TODO DisplayView guy
// displayView(position);
}
}
}
I am trying to add icons to my Navigation Drawer in Android. I have the following code in my main
public class MainActivity extends ActionBarActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private myAdapter MyAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
String[] osArray = {"Math", "Physics", "Chemistry"};
MyAdapter = new myAdapter(this);
mDrawerList.setAdapter(MyAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position) {
case 0:
Intent a = new Intent(MainActivity.this, MathActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(MainActivity.this, PhysicsActivity.class);
startActivity(b);
break;
case 2:
Intent c = new Intent(MainActivity.this, ChemistryActivity.class);
startActivity(c);
break;
default:
}
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
class myAdapter extends BaseAdapter {
private Context context;
String SchoolCategories[];
int[] images = {R.drawable.math_icon,R.drawable.physics_icon,R.drawable.chemistry_icon};
public myAdapter(Context context){
this.context = context;
SchoolCategories = context.getResources().getStringArray(R.array.school);
}
#Override
public int getCount() {
return SchoolCategories.length;
}
#Override
public Object getItem(int position) {
return SchoolCategories[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.custom_row, parent, false);
}
else{
row =convertView;
}
TextView titleTextView =(TextView) row.findViewById(R.id.textViewRow1);
ImageView titleImageView = (ImageView) row.findViewById(R.id.imageViewRow1);
titleTextView.setText(SchoolCategories[position]);
titleImageView.setImageResource(images[position]);
return row;
}
}
}
And the following XML Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/math_icon"
android:id="#+id/imageViewRow1"
/>
<TextView
android:layout_margin="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textViewRow1"
/>
</LinearLayout>
I am simple just trying to add icons to the navigation drawer, but this does not work and I am not sure what goes wrong. The application just shuts down. All help is really appreciated!
Here is my log-cat:
05-25 12:27:33.053 3909-3909/oscarorellana.nowwetryitmyway.physicsproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: oscarorellana.nowwetryitmyway.physicsproject, PID: 3909
android.content.ActivityNotFoundException: Unable to find explicit activity class {oscarorellana.nowwetryitmyway.physicsproject/oscarorellana.nowwetryitmyway.physicsproject.MathActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1761)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1485)
at android.app.Activity.startActivityForResult(Activity.java:3736)
at android.app.Activity.startActivityForResult(Activity.java:3697)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:820)
at android.app.Activity.startActivity(Activity.java:4007)
at android.app.Activity.startActivity(Activity.java:3975)
at oscarorellana.nowwetryitmyway.physicsproject.MainActivity$1.onItemClick(MainActivity.java:57)
This was solved with changing this line:
inflater.inflate(R.layout.custom_row, parent, false);
To this line:
row = inflater.inflate(R.layout.custom_row, parent, false);
I am having some problem with navigation drawer in Android. So these are the codes with me:
public class NavigationDrawer extends FragmentActivity {
private String[] drawerListViewItems;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private ActionBarDrawerToggle actionBarDrawerToggle;
protected DrawerLayout fullLayout;
protected FrameLayout actContent;
#Override
public void setContentView(final int layoutResID) {
fullLayout = (DrawerLayout) getLayoutInflater().inflate(
R.layout.navigation_drawer, null); // Your base layout here
actContent = (FrameLayout) fullLayout.findViewById(R.id.act_content);
getLayoutInflater().inflate(layoutResID, actContent, true);
super.setContentView(fullLayout);
drawerListViewItems = getResources().getStringArray(R.array.items);
drawerListView = (ListView) findViewById(R.id.left_drawer);
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,
drawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
drawerListView.bringToFront();
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position,
long id) {
switch (position) {
}
drawerLayout.closeDrawer(drawerListView);
}
}
}
And my xml file:
<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" >
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:divider="#CCCCCC"
android:dividerHeight="0.5dp"
android:paddingLeft="16dp"
android:paddingRight="16dp" />
<FrameLayout
android:id="#+id/act_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
And the string file where I declare the words for navigation drawer item:
<string-array name="items">
<item>Dashboard</item>
<item>Account</item>
<item>Setting</item>
<item>Recurring</item>
<item>Budget</item>
</string-array>
But with these code, the navigation drawer level is only one. What I am trying to do is there will be still sub item under Dashboard, Setting and Budget.
I wonder how to modify it so that the navigation drawer could take in one more level of items.
Thanks in advance.
EDIT
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
// private ListView mDrawerList;
private ExpandableListView mDrawerList;
private LinearLayout navDrawerView;
CustomExpandAdapter customAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mAnalyzeEventSelection;
private int selectedPosition;
List<SampleTO> listParent;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
navDrawerView = (LinearLayout) findViewById(R.id.navDrawerView);
mAnalyzeEventSelection = getResources().getStringArray(R.array.analyzeEvent_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.nav_left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
listParent = new ArrayList<SampleTO>();
listDataChild = new HashMap<String, List<String>>();
// Navigation Drawer of Flight starts
listParent.add(new SampleTO(getString(R.string.createEventDrawer), R.drawable.sun));
listParent.add(new SampleTO(getString(R.string.analyzeEventDrawer), R.drawable.solar_system));
listParent.add(new SampleTO(getString(R.string.qrCodeDrawer), R.drawable.moon));
listDataChild.put(getString(R.string.createEventDrawer), new ArrayList<String>());
listDataChild.put(getString(R.string.qrCodeDrawer), new ArrayList<String>());
listDataChild.put(getString(R.string.analyzeEventDrawer), Arrays.asList(mAnalyzeEventSelection));
customAdapter = new CustomExpandAdapter(this, listParent, listDataChild);
// setting list adapter
mDrawerList.setAdapter(customAdapter);
mDrawerList.setChoiceMode(ExpandableListView.CHOICE_MODE_SINGLE);
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
/* if (savedInstanceState == null) {
selectItem(0);
}*/
}
#Override
protected void onResume() {
super.onResume();
mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForGroup(groupPosition));
parent.setItemChecked(index, true);
String parentTitle = ((SampleTO) customAdapter.getGroup(groupPosition)).getTitle();
if (parentTitle.equals(getString(R.string.createEventDrawer))){
Toast.makeText(
MainActivity.this,
"Create Event",
Toast.LENGTH_LONG).show();
setTitle(mAnalyzeEventSelection[selectedPosition]);
}
else if (parentTitle != getString(R.string.analyzeEventDrawer)) {
mDrawerLayout.closeDrawer(navDrawerView);
}
return false;
}
});
mDrawerList.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForChild(groupPosition, childPosition));
parent.setItemChecked(index, true);
selectItem(childPosition);
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(navDrawerView);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
private void selectItem(int position) {
selectedPosition = position;
mDrawerLayout.closeDrawer(navDrawerView);
switch(selectedPosition){
case 0:
Toast.makeText(
MainActivity.this,
"Event Pop",
Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(
MainActivity.this,
"Buffer",
Toast.LENGTH_LONG).show();
break;
}
setTitle(mAnalyzeEventSelection[selectedPosition]);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
And my string file:
<resources>
<string name="app_name">Navigation Drawer Example</string>
<string name="createEventDrawer">Create Event</string>
<string name="analyzeEventDrawer">Analyze Event</string>
<string-array name="analyzeEvent_array">
<item>Past Event Population</item>
<item>Buffer</item>
</string-array>
<string name="qrCodeDrawer">QR Code Scan</string>
<string name="drawer_open">Open navigation drawer</string>
<string name="drawer_close">Close navigation drawer</string>
<string name="action_websearch">Web search</string>
<string name="app_not_available">Sorry, there\'s no web browser available</string>
<string name="_11">11</string>
Steps:
Change ListView to Expandablelistview.
Add subitems for the group items required.
Example :Custom Navigation Drawer