How do I use the navigation drawer to select a viewpager - java

I'm completely new to android app development and I'm currently working on a project for school.
From my understanding so far, you can use the navigation drawer to swap out UI fragments.
I made a nav drawer that's working properly so far based on the tutorial given here:
https://developer.android.com/training/implementing-navigation/nav-drawer.html
I'm trying to have it switch views for each item that's selected. I made a view pager fragment activity and I want the program to replace the view with my view pager upon selecting the 4th item in the nav drawer (index 3). I added a switch statement in my fragment class to determine which layout to load.
Here's the activity for the nav drawer:
package com.mkge.mkg;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitle;
private String[] mPageTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = getTitle();
mPageTitles = getResources().getStringArray(R.array.nav_draw_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPageTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
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(R.string.drawer_open);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(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<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putInt(PageFragment.ARG_PAGE_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
setTitle(mPageTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
public static class PageFragment extends Fragment {
public static final String ARG_PAGE_NUMBER = "page_number";
public PageFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int i = getArguments().getInt(ARG_PAGE_NUMBER);
View rootView;
switch(i) {
case 0:
rootView = inflater.inflate(R.layout.page_home, container, false);
break;
case 1:
rootView = inflater.inflate(R.layout.page_services, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.page_packages, container, false);
break;
case 3:
View view = new MeetViewPager().getViewPager();
rootView = view;
break;
case 4:
rootView = inflater.inflate(R.layout.page_about, container, false);
break;
case 5:
rootView = inflater.inflate(R.layout.page_contact, container, false);
break;
case 6:
rootView = inflater.inflate(R.layout.page_extras, container, false);
break;
default:
rootView = null;
}
String page = getResources().getStringArray(R.array.nav_draw_array)[i];
getActivity().setTitle(page);
return rootView;
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I made this fragment activity here to create the view pager. I tried taking the view pager object I made here and passing it to the switch statement to my nav drawer activity.
package com.mkge.mkg;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
#SuppressLint("ValidFragment")
public class MeetViewPager extends FragmentActivity {
public ViewPager mViewPager;
public FragmentPagerAdapter mViewPagerAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page_meet);
List<Fragment> fragments = getFragments();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPagerAdapter = new mPageAdapter(getSupportFragmentManager(), fragments);
mViewPager.setAdapter(mViewPagerAdapter);
}
public View getViewPager() {
return mViewPager;
}
private List<Fragment> getFragments() {
List<Fragment> fList = new ArrayList<Fragment>();
Fragment fragment = new mFragment();
Bundle args = new Bundle();
args.putInt("position", 0);
fragment.setArguments(args);
fList.add(fragment);
fragment = new mFragment();
args = new Bundle();
args.putInt("position", 1);
fragment.setArguments(args);
fList.add(fragment);
return fList;
}
private class mPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public mPageAdapter(FragmentManager f, List<Fragment> fragments) {
super(f);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
#SuppressLint("ValidFragment")
public static class mFragment extends Fragment {
public mFragment() {
}
public static final mFragment newInstance(int i) {
mFragment f = new mFragment();
Bundle args = new Bundle(1);
args.putInt("position", i);
f.setArguments(args);
return f;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v;
int i = getArguments().getInt("postion");
switch(i) {
case 0:
v = inflater.inflate(R.layout.page_meet_0, container, false);
break;
case 1:
v = inflater.inflate(R.layout.page_meet_1, container, false);
break;
default:
v = null;
}
return v;
}
}
}
Any help would be appreciated thanks.

mViewPager.setCurrentItem(0);
This should be all you need to make your ViewPager change to the first tab.
This would be called from inside your selectItem() method.

Related

Android fragment tabbed layout, reselecting tab 3, listview disappears

When I select tab 3 my listview appears, yet when I select tab 1 and reselect tab 3, the listview doesn't appear.
Why is this?
https://github.com/jdavey1996/News-Android-App
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Local"));
tabLayout.addTab(tabLayout.newTab().setText("Top rated"));
tabLayout.addTab(tabLayout.newTab().setText("All"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
package com.josh_davey.news_app;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentAdapter extends FragmentPagerAdapter {
int count;
public FragmentAdapter(FragmentManager fm, int count) {
super(fm);
this.count = count;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment1 temp = new Fragment1();
return temp;
case 1:
Fragment2 temp2 = new Fragment2();
return temp2;
case 2:
Fragment3 temp3 = new Fragment3();
return temp3;
}
return null;
}
#Override
public int getCount() {
return count;
}
}
package com.josh_davey.news_app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment3 extends Fragment {
public Fragment3() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GetData getData = new GetData(getContext(),getActivity());
getData.execute("lincoln");
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment3, container, false);
}
}
If you need link to the full code it's on my github. Thanks in advance for any help
https://github.com/jdavey1996/News-Android-App
Default ViewPager's offscreenPageLimit is 1. So the tab3 is detached when tab1 is re-selected. If fragment is detached, Fragment's views are destroyed.
see: ViewPager.setOffscreenPageLimit
So I recommend you to set offscreenPageLimit to 2.
viewPager.setOffscreenPageLimit(2);
Or you can hold the list of ArticleConstructor in Fragment3 like blew.
GetData.java:
public class GetData extends AsyncTask<String, String,ArrayList<ArticleConstructor>>{
Callback callback;
interface Callback {
void onArticleConstructorLoaded(ArrayList<ArticleConstructor> articleConstructors);
}
public GetData(Callback callback) {
this.callback = callback;
}
...
#Override
protected void onPostExecute(ArrayList<ArticleConstructor> result) {
callback.onArticleConstructorLoaded(result);
}
....
}
Fragment3.java:
public class Fragment3 extends Fragment implements GetData.Callback {
private ListView listView;
private ArrayList<ArticleConstructor> articleConstructors = new ArrayList<>();
private ArticleArrayAdapter adapter;
public Fragment3() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment3, container, false);
listView = (ListView) view.findViewById(R.id.listView);
adapter = new ArticleArrayAdapter(getActivity(), getContext(), articleConstructors);
listView.setAdapter(adapter);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (articleConstructors.size() == 0) {
GetData getData = new GetData(this);
getData.execute("lincoln");
}
}
#Override
public void onArticleConstructorLoaded(ArrayList<ArticleConstructor> articleConstructors) {
this.articleConstructors = articleConstructors;
adapter.setArticleConstructors(articleConstructors);
}
}

Icons in Tabs with tabbed activity (Android Studio)

i want to put icons instead of text in the tabs. I'm using the tabbed activity and here is the code of the mainactivity.java
package com.example;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
return FragmentOne.newInstance("a","b");
case 1:
return FragmentTwo.newInstance("a","b");
case 2:
return FragmentThree.newInstance("a","b");
case 3:
return FragmentFour.newInstance("a","b");
case 4:
return FragmentFive.newInstance("a","b");
default:
return FragmentThree.newInstance("a","b");
}
}
#Override
public int getCount() {
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "One";
case 1:
return "Two";
case 2:
return "Three";
case 3:
return "Four";
case 4:
return "Five";
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
I tried a lot with code and examples i found on the internet but nothing worked.

navigation drawer layout the title in the toolbar not changing

In the mTitle is not showing effect on the toolbar when a fragment is selected according to the fragment name specified in mTitle. It is just showing the app name in every fragment. please help!!!!
MainActivity.java
import android.app.Activity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
//FragmentManager fragmentManager = getSupportFragmentManager(); // For AppCompat use getSupportFragmentManager
switch(position) {
default:
case 0:
fragment = new home();
break;
case 1:
fragment = new academics();
break;
case 2:
fragment = new about();
break;
case 3:
fragment = new student();
break;
case 4:
fragment = new alumini();
break;
case 5:
fragment = new events();
break;
case 6:
fragment = new media();
break;
case 7:
fragment = new contact();
break;
}
/* fragmentManager.beginTransaction()
.replace(R.id.container,fragment )
.commit();*/
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
}
/* // update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();*/
}
public void onSectionAttached(int number) {
switch (number) {
default:
case 1:
mTitle = getString(R.string.home);
break;
case 2:
mTitle = getString(R.string.academics);
break;
case 3:
mTitle = getString(R.string.about);
break;
case 4:
mTitle = getString(R.string.student);
break;
case 5:
mTitle = getString(R.string.alumni);
break;
case 6:
mTitle = getString(R.string.events);
break;
case 7:
mTitle = getString(R.string.media);
break;
case 8:
mTitle = getString(R.string.contact);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
NavigationDrawerFragment.java
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.home),
getString(R.string.academics),
getString(R.string.about),
getString(R.string.student),
getString(R.string.alumni),
getString(R.string.events),
getString(R.string.media),
getString(R.string.contact),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
events.java (one of the fragment java files )
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by sukhvir on 17/04/2015.
*/
public class events extends android.support.v4.app.Fragment {
public events(){}
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate the layout for this fragment
*/
return inflater.inflate(
R.layout.events, container, false);
}
}
public void onSectionAttached(int number) {
switch (number) {
default: //Default should not be here.
case 1:
mTitle = getString(R.string.home);
break;
...
case 8:
mTitle = getString(R.string.contact);
break;
}
}
Fix the code above.
Your "events" Fragment class never calls onSectionAttached, this is a part of the implementation for the interface in PlaceholderFragment, which is created as a guideline. You should code your Fragments in a similar fashion and implement their corresponding interfaces.
Inside your Fragment:
events.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by sukhvir on 17/04/2015.
*/
public class events extends android.support.v4.app.Fragment {
public events(){}
private static final int ARG_SECTION_NUMBER = 5;
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate the layout for this fragment
*/
return inflater.inflate(
R.layout.events, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
ARG_SECTION_NUMBER);
}
}
and in:
MainActivity.java
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.home);
break;
case 2:
mTitle = getString(R.string.academics);
break;
case 3:
mTitle = getString(R.string.about);
break;
case 4:
mTitle = getString(R.string.student);
break;
case 5:
mTitle = getString(R.string.alumni);
break;
case 6:
mTitle = getString(R.string.events);
break;
case 7:
mTitle = getString(R.string.media);
break;
case 8:
mTitle = getString(R.string.contact);
break;
}
setTitle();
}
private void setTitle() {
getSupportActionBar().setTitle(mTitle);
}
I hope you get the idea.
The code above just works, you might want to understand the flow and clean up.

Applicable for the Arguments location Manager Error

I'm relatively new to both Java and the android platform and I have come across a problem in my code that is just completely beyond me. I am trying to lock onto a users location and move the camera to that location using the google maps api v2 however this is without success even with constant reading of resources and attempts.
The method requestLocationUpdates(String, long, float, LocationListener) in the type >LocationManager is not applicable for the arguments (String, int, int, LocationListener) >MainActivity.java /Loca/src/com/afrostudio/loca line 91 Java Problem
Also a very recent error has randomly occured:
R cannot be resolved to a variable
Any help would be fantastic please :)
package com.afrostudio.loca;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.MapFragment;
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private GoogleMap map;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
public class googleMap extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// Define a listener that responds to location updates
LocationListener locationListner = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latti = location.getLatitude();
double longi = location.getLongitude();
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(latti,
longi));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
map.moveCamera(center);
map.animateCamera(zoom);
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListner);
}
#Override
public void onDestroyView()
{
super.onDestroyView();
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
}
public class MyFragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile, container, false);
}
}
public class MyFragment3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_settings, container, false);
}
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = new googleMap();
FragmentManager fragmentManager = getFragmentManager();
switch(position) {
case 1:
fragment = new googleMap();
break;
case 2:
fragment = new MyFragment2();
break;
case 3:
fragment = new MyFragment3();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
ActionBar ab = getActionBar();
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#A4C639"));
ab.setBackgroundDrawable(colorDrawable);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
The R error thing has to do with your xml files (layouts) check them carefully. Try cleaning the project as well... As for the Location I sugest you to use the LocationClient, it is newer and performs better... https://developer.android.com/training/location/receive-location-updates.html

Launch a activity with button click using a FragmentActivity

Hey guys I need help I'm making a launcher that needs to have a button that when clicked it opens the AllApps.class activity witch shows a list of all installed apps
The other button needs to open a installed app that is on the device
and the last button needs to open the default web browser and open google.com
Here's my code!
Home.java:
package com.dva.schooltoolshome;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
public class Home extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
^ ActionBar.DISPLAY_SHOW_TITLE);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("calc")) {
actionBar.addTab(actionBar.newTab()
.setIcon(R.drawable.calendar)
.setTabListener(this));
} else if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("home")) {
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.home)
.setTabListener(this));
} else if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("drive")) {
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.folder)
.setTabListener(this));
}
}
mViewPager.setCurrentItem(1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_SETTINGS));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new CalcFragment();
break;
case 1:
fragment = new HomeFragment();
break;
case 2:
fragment = new DriveFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static class HomeFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_homebar,
container, false);
return rootView;
}
}
public static class CalcFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public CalcFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_calculator,
container, false);
return rootView;
}
}
public static class DriveFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DriveFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText("DRIVE");
return rootView;
}
}
}
activity_homebar
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".HomeBar" >
<ImageButton
android:id="#+id/apps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/appdrawer"
android:src="#drawable/appdrawer" />
<ImageButton
android:id="#+id/wbrowser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/apps"
android:src="#drawable/browser" />
</RelativeLayout>
AllApps.java:
package com.dva.schooltoolshome;
import android.app.LauncherActivity;
import android.content.Intent;
public class AllApps extends LauncherActivity {
#Override
protected Intent getTargetIntent () {
// just a example, you should replace the method yourself
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
}
I'm am still learning so please don't judge
Thanks in advance
Regards
Rapsong11
You can easily find the answer to your question with a bit of googling. It has been asked many times before. I will point you in the right direction.
To add functionality to a button you have to first make the button (view) aware it can be clicked. This can be done in java programatically (research this yourself) or in the xml like so:
android:onClick="onClickDoStuff"
Then you have to implement the onClickDoStuff method which will look like:
public void onClickDoStuff(View view) {
//Do stuff on click
}
You wanted the button to open a new activity onClick to do that you would require an intent have a look here for futher guidance

Categories

Resources