Why tabs are not visible inside fragment? - android

In my app I want to use swipe views of four tabs inside a fragment. The four tabs are contains different fragments each and all the four fragments are sliding by swipe from right to left or vice versa. The fragments are working fine but the tabs are not visible within the fragment. Anyone have any solution for this. Thanks in advance :)
this is the main fragment which contains the tabs:-
public class DashboardTabFragment extends Fragment implements ActionBar.TabListener {
private static final String ARG_SECTION_NUMBER = "arg_section_number";
private String[] tabTitle = {"Cleanness", "Product Display", "Hygiene", "Asm Visits"};
public static DashboardTabFragment newInstance(int position) {
DashboardTabFragment fragment = new DashboardTabFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
return fragment;
}
private ViewPager viewPager;
public DashboardTabFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard_tab, container, false);
setHasOptionsMenu(true);
ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
assert actionBar != null;
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
TabPageAdapter tabPageAdapter = new TabPageAdapter(getActivity().getSupportFragmentManager(), getActivity());
viewPager.setAdapter(tabPageAdapter);
for (String aTabTitle : tabTitle)
actionBar.addTab(actionBar.newTab().setText(aTabTitle).setTabListener(this));
return rootView;
}
This is the adapter for fragments:-
public class TabPageAdapter extends FragmentPagerAdapter {
Context context;
public TabPageAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CleannessChartFragment(context);
case 1:
return new ProductDisplayChartFragment(context);
case 2:
return new HygieneChartFragment(context);
case 3:
return new AsmVisitsChartFragment(context);
}
return null;
}
#Override
public int getCount() {
return 4;
}

I found the solution. I used TabHost for tabs with viewpager.
This is my fragment :-
package com.itpp.trt;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TabHost;
public class DashboardTabFragment extends Fragment implements ViewPager.OnPageChangeListener {
private static final String ARG_SECTION_NUMBER = "arg_section_number";
private ViewPager mViewPager;
private TabHost tabHost;
private String[] tabSpec = {"Tab_1", "Tab_2", "Tab_3", "Tab_4"};
private String[] tabTitle = {"Cleanness", "Product Display", "Hygiene", "Asm Visits"};
private TabHost.TabContentFactory mFactory = new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
View v = new View(getActivity());
v.setMinimumHeight(0);
return v;
}
};
public static DashboardTabFragment newInstance(int position) {
DashboardTabFragment fragment = new DashboardTabFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
return fragment;
}
public DashboardTabFragment() {
tabHost = null;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard_tab, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.pager);
mViewPager.setAdapter(new TabPageAdapter(getChildFragmentManager(), getActivity()));
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
tabHost.setup();
mViewPager.setOnPageChangeListener(this);
for (int i = 0; i < tabSpec.length; i++) {
tabHost.addTab(tabHost.newTabSpec(tabSpec[i]).setIndicator(tabTitle[i]).setContent(mFactory));
}
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
if (tabId.equals("Tab_1")) {
mViewPager.setCurrentItem(0);
} else if (tabId.equals("Tab_2")) {
mViewPager.setCurrentItem(1);
} else if (tabId.equals("Tab_3")) {
mViewPager.setCurrentItem(2);
} else if (tabId.equals("Tab_4")) {
mViewPager.setCurrentItem(3);
}
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MyActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onDetach() {
super.onDetach();
}
}
This is my tabpager adapter :-
package com.itpp.trt;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by biswajit on 28-11-14.
*/
public class TabPageAdapter extends FragmentStatePagerAdapter{
Context context;
public TabPageAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CleannessChartFragment(context);
case 1:
return new ProductDisplayChartFragment(context);
case 2:
return new HygieneChartFragment(context);
case 3:
return new AsmVisitsChartFragment(context);
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
Hope this helps other. Thanks :)

Related

How to switch between two fragments in android TabLayout?

how to switch between Fragment A and Fragment B in android TabLayout.
how to switch to next Fragment when Fargment Button Onclick is called.
Please help me
package com.digi.global.globalhub.fragment.offer;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.digi.global.globalhub.R;
import com.digi.global.globalhub.Utility.M;
import com.digi.global.globalhub.listener.FilterListener;
import com.digi.global.globalhub.listener.FragmentMove;
import com.digi.global.globalhub.listener.OfferFilter;
public class OfferFragmentActivity extends Fragment implements View.OnClickListener{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
PagerAdapter adapter;
ViewPager viewPager;
TabLayout tabLayout;
Context context;
Toolbar toolbar;
ImageView bizMenu;
PopupMenu popup;
public static OfferFragmentActivity mInstance = null;
public OfferFragmentActivity() {
// Required empty public constructor
}
public static OfferFragmentActivity newInstance(String param1, String param2) {
OfferFragmentActivity fragment = new OfferFragmentActivity();
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);
}
context = this.getContext();
mInstance = this;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view =inflater.inflate(R.layout.fragment_offer, container, false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new PagerAdapter(getChildFragmentManager(), getContext());
tabLayout = (TabLayout) view.findViewById(R.id.tablayout);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
bizMenu = (ImageView) view.findViewById(R.id.bizMenu);
bizMenu.setVisibility(View.VISIBLE);
bizMenu.setOnClickListener(this);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
//toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.biz_ic, android.R.style.Theme_DeviceDefault));
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.mipmap.ic_menu_white_36dp);
upArrow.setColorFilter(Color.parseColor("#B68426"), PorterDuff.Mode.SRC_ATOP);
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeAsUpIndicator(upArrow);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getString(R.string.Offers));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(final TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
#Override
public void onClick(View v) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Fragment fragment = (Fragment) adapter.instantiateItem(viewPager, viewPager.getCurrentItem());
if(fragment instanceof OfferFilter){
switch (item.getItemId()) {
case R.id.bizTravel:
((OfferFilter) fragment).onFilterBizTravel("bizTravel");
return true;
case R.id.bizAssistance:
((OfferFilter) fragment).onFilterAssistance("bizAssistance");
return true;
case R.id.bizSolution:
((OfferFilter) fragment).onFilterSolution("bizSolution");
return true;
case R.id.partners:
((OfferFilter) fragment).onFilterPartner("partners");
return true;
case R.id.favoutites:
((OfferFilter) fragment).onFilterFavouritesBiz("favoutites");
return true;
}
return false;
}
return super.onOptionsItemSelected(item);
}
class PagerAdapter extends FragmentStatePagerAdapter {
String tabTitles[] = getResources().getStringArray(R.array.offerTab);
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
/* FragmentMove fragmentChanges = (FragmentMove) adapter.instantiateItem(viewPager, 2);
if(fragmentChanges instanceof FragmentMove) {
((FragmentMove) fragmentChanges).fragmentChanges();
}*/
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTWO();
case 2:
return new FragmentThree();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
/* public View getTabView(int position) {
View tab = LayoutInflater.from(getContext()).inflate(R.layout.tab_text_layout, null);
TextView tv = (TextView) tab.findViewById(R.id.tabText);
tv.setText(tabTitles[position]);
return tab;
}*/
}
}
You can have a FragmentPagerAdapter to manager fragments and set this adapter into viewPager to slide fragments when you click on tabs or swipe to change tabs.
FragmentPagerAdapter:
public class TabLayoutViewPagerAdapter extends FragmentPagerAdapter {
private final int PAGE_COUNT = 3;
private final String[] mTabsTitle = {"Fragment A", "Fragment B, "Fragment C"};
private Context context;
private int[] mTabsIcons = {
R.drawable.a,
R.drawable.b,
R.drawable.c};
public TabLayoutViewPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
public View getTabView(int position) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
TextView title = (TextView) view.findViewById(R.id.title);
title.setText(mTabsTitle[position]);
title.setSingleLine(true);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
icon.setImageResource(mTabsIcons[position]);
return view;
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
return new FragmentA();
case 1:
return new FragmentB();
case 2:
return new FragmentC();
}
return null;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return mTabsTitle[position];
}}
How you use it:
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
TabLayoutViewPagerAdapter pagerAdapter = new TabLayoutViewPagerAdapter(getSupportFragmentManager(), this);
if (viewPager != null) {
viewPager.setAdapter(pagerAdapter);
}
You need a TabLayout:
mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
if (mTabLayout != null) {
mTabLayout.setupWithViewPager(viewPager);
//populate your tabs
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
if (tab != null)
tab.setCustomView(pagerAdapter.getTabView(i));
}
TabLayout.Tab tab = mTabLayout.getTabAt(0);
if (tab != null && tab.getCustomView() != null) {
tab.getCustomView().setSelected(true);
}
}
How to select a page:
private void selectPage(int pageIndex) {
mTabLayout.setScrollPosition(pageIndex, 0f, true);
viewPager.setCurrentItem(pageIndex);
}
Do not forget to create your customTab.xml.
Best regards.
In Fragment A's onClick() method, try this :
TabActivity tabs = (TabActivity) getParent();
tabs.getTabHost().setCurrentTab(2);

creating a fragment hit counter

I have a really basic app that has three fragments - fragments a,b and c, each of these fragments contains a piece of text that reads "I have been visited " + tallyVariable + " this many times".
I'm not entirely sure this is the correct way of doing it as I am new to app development and fairly new to the java language, but have attempted to give it a go.
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.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends FragmentActivity {
//tally variables
public int numSwipes = 0;
public int numSwipes2 = 0;
public int numSwipes3 = 0;
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
}
class MyAdapter extends FragmentStatePagerAdapter{
// reference to MainActivity and variables
MainActivity mainActivity = new MainActivity();
int fragNumSwipes = mainActivity.numSwipes;
int fragNumSwipes2 = mainActivity.numSwipes2;
int fragNumSwipes3 = mainActivity.numSwipes3;
public MyAdapter(FragmentManager fm) {
super(fm);
}
//#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if(i==0)
{
fragment = new FragmentA();
fragNumSwipes++;
}
if(i==1)
{
fragment = new FragmentB();
fragNumSwipes2++;
}
if(i==2)
{
fragment = new FragmentC();
fragNumSwipes3++;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position){
if(position==0)
{
return "tab 1";
}
if(position==1)
{
return "tab 2";
}
if(position==2)
{
return "tab 3";
}
return null;
}
}
below is the code for one of the fragments (code for the rest of the fragments is identical).
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentA extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a,container,false);
}
// MyAdapter adapterVariables = new MyAdapter();
}
I have commented out the above variable declaration "adapterVariables", but when it is active, it will not let me create a reference to the MyAdapter class where the tally variables now exist? what am I missing, I think it expects something between the parenthesis?
MainActivity mainActivity = new MainActivity(); this does not create a reference to your MainActivity! The same goes for your fragments code. You are creating new instances of your classes. You can pass references in your constructors. But for your idea, you won't need this. Below, you can find a corrected version, if you have questions about it, feel free to ask!
public class MainActivity extends FragmentActivity {
//tally variables
private int numSwipes = 0;
private int numSwipes2 = 0;
private int numSwipes3 = 0;
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
//instead of increasing the number in the adapter, add a listener, since this is a better place to do it.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch(position){
case 0:
numSwipes++;
break;
case 1:
numSwipes2++;
break;
case 2:
numSwipes3++;
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position){
if(position==0)
{
return "tab 1";
}
if(position==1)
{
return "tab 2";
}
if(position==2)
{
return "tab 3";
}
return null;
}
}

How to add Tabhost in Navigation Drawer

In my app I am using navigation drawer from this tutorial http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
Now I am trying to add tabhost with fragment,but its not working
it shows error here tabss.setViewPager(mViewPager);
Cannot resolve method setviewpager(android.support.v4.view.viewpager)
public class All_Product_Details extends Fragment {
private TabHost mTabHost;
private ViewPager mViewPager;
private YourAdapter mTabsAdapter;
private Button descr;
private TextView general_desc;
private TextView short_desc;
private TextView full_desc;
private Button btn_add_to_cart;
public All_Product_Details(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.all_product_detais, container, false);
mViewPager = (ViewPager)rootView.findViewById(R.id.viewpager);
mTabsAdapter= new YourAdapter(getFragmentManager());
mViewPager.setAdapter(mTabsAdapter);
TabWidget tabss = (TabWidget)rootView.findViewById(R.id.tabs);
tabss.setViewPager(mViewPager);
general_desc=(TextView)rootView.findViewById(R.id.general_desc);
short_desc=(TextView)rootView.findViewById(R.id.short_desc);
full_desc=(TextView)rootView.findViewById(R.id.full_desc);
btn_add_to_cart=(Button)rootView.findViewById(R.id.btn_addtocart);
btn_add_to_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Add_to_cart tf = new Add_to_cart();
android.support.v4.app.FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
short_desc.setVisibility(View.GONE);
full_desc.setVisibility(View.GONE);
descr=(Button)rootView.findViewById(R.id.all_prod_description);
descr.setBackgroundResource(R.drawable.hidebackground);
descr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (flag == 0) {
descr.setBackgroundResource(R.drawable.showbackground);
//lnrallbtns.setVisibility(View.GONE);
general_desc.setVisibility(View.GONE);
flag++;
} else {
descr.setBackgroundResource(R.drawable.hidebackground);
// lnrallbtns.setVisibility(View.VISIBLE);
general_desc.setVisibility(View.VISIBLE);
short_desc.setVisibility(View.GONE);
full_desc.setVisibility(View.GONE);
flag = 0;
}
}
});
return rootView;
}
public class YourAdapter extends FragmentStatePagerAdapter {
private String[] titles = { "Item 1", "Item 2", "Item 3" };
public YourAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch(i){
case 0:{
return new FragementA();
}case 1:{
return new FragmentB();
}case 2:{
return new FragmentC();
}
}
}
#Override
public int getCount() {
return titles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
I found and referred an awsm example called Balaji-K13 .
You can add whatever your list in here like:
Inside MainActivity.java
package com.webileapps.navdrawer;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class MainActivity extends SherlockFragmentActivity {
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// 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
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
break;
}
case R.id.action_contact:
// QuickContactFragment dialog = new QuickContactFragment();
// dialog.show(getSupportFragmentManager(), "QuickContactFragment");
// return true;
}
return super.onOptionsItemSelected(item);
}
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(int position) {
switch (position) {
case 0:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content,
PageSlidingTabStripFragment.newInstance(),
PageSlidingTabStripFragment.TAG).commit();
break;
default:
SherlockFragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.add(R.id.content, fragment).commit();
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
Inside PageSlidingTabStripFragment.java
package com.webileapps.navdrawer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
import com.astuetz.PagerSlidingTabStrip;
public class PageSlidingTabStripFragment extends Fragment {
public static final String TAG = PageSlidingTabStripFragment.class
.getSimpleName();
public static PageSlidingTabStripFragment newInstance() {
return new PageSlidingTabStripFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.pager, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) view
.findViewById(R.id.tabs);
ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
private final String[] TITLES = { "Categories", "Home", "Top Paid",
"Top Free" };
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public SherlockFragment getItem(int position) {
return SuperAwesomeCardFragment.newInstance(position);
}
}
}
Inside PlanetFragment.java
package com.webileapps.navdrawer;
import java.util.Locale;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.actionbarsherlock.app.SherlockFragment;
public class PlanetFragment extends SherlockFragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container,
false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(
planet.toLowerCase(Locale.getDefault()), "drawable",
getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image))
.setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
And finally SuperAwesomeCardFragment.java
package com.webileapps.navdrawer;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class SuperAwesomeCardFragment extends SherlockFragment{
private static final String ARG_POSITION = "position";
private int position;
public static SuperAwesomeCardFragment newInstance(int position) {
SuperAwesomeCardFragment f = new SuperAwesomeCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
FrameLayout fl = new FrameLayout(getActivity());
fl.setLayoutParams(params);
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources()
.getDisplayMetrics());
TextView v = new TextView(getActivity());
params.setMargins(margin, margin, margin, margin);
v.setLayoutParams(params);
v.setLayoutParams(params);
v.setGravity(Gravity.CENTER);
v.setBackgroundResource(R.drawable.background_card);
v.setText("CARD " + (position + 1));
fl.addView(v);
return fl;
}
}
Hope this Helped :)

Camera opening on two different tabs

I am fairly new to developing Android applications. I am trying to create an application that allows you to save a picture in the "Pictures" folder named Property_Picture.jpg using the last (camera) tab. However, both the last two tabs are opening the camera, and the picture is also not being saved once you take a picture. Any help would be greatly appreciated. Thank you!
Here is my code:
package com.example.prcentry02;
import java.io.File;
import java.util.Locale;
import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v13.app.FragmentPagerAdapter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
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.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
getFragmentManager();
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
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++) {
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#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) {
if (position== mSectionsPagerAdapter.getCount()-1)
{
return CameraFragment.newInstance(position);
}
else if (position== 0)
{
return LocationFragment.newInstance(position);
}
else
{
return propertyrecordFragment.newInstance(position);
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.PRC_Location).toUpperCase(l);
case 1:
return getString(R.string.PRC_1).toUpperCase(l);
case 2:
return getString(R.string.PRC_2).toUpperCase(l);
case 3:
return getString(R.string.Camera).toUpperCase(l);
}
return null;
}
}
public static class LocationFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static LocationFragment newInstance(int sectionNumber) {
LocationFragment fragment = new LocationFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public LocationFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.location_main, container,false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText("Location" + this.getArguments());
return rootView;
}
}
public static class CameraFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static CameraFragment newInstance(int sectionNumber) {
CameraFragment fragment = new CameraFragment();
Bundle args = new Bundle();
args.putInt(CameraFragment.ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public CameraFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.camera_main, container,false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText("camera" + ARG_SECTION_NUMBER);
Context context = getActivity();
PackageManager packageManager = context.getPackageManager();
if(packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA) == false){
Toast.makeText(getActivity(), "This device does not have a camera.", Toast.LENGTH_SHORT)
.show();
}
Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File image = new File("~/Pictures/", "Property_Picture.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent,0);
return rootView;
}
}
public static class propertyrecordFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static propertyrecordFragment newInstance(int sectionNumber) {
propertyrecordFragment fragment = new propertyrecordFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public propertyrecordFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.propertyrecordcard_main, container,false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText("PRC goes here");
return rootView;
}
}
}

Where to place MediaPlayer in a fragment?

I would like to make my sound file play automatically when I arrive at a new fragment (by swiping). Right now, the sound doesn't play. Is there perhaps a fundamental difference between
public void OnAttach(Activity Fragment1){
and
public void OnAttach(Fragment Fragment1){
Thanks for any help. Code:
package com.example.test21;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.media.MediaPlayer;
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.View;
import android.view.ViewGroup;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
actionBar.hide();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
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++) {
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#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) {
switch (position) {
case 0:
return new Fragment0();
case 1:
return new Fragment1();
case 2:
return new Fragment2();
default:
return null;
}}
#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 Fragment0 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_0, null);
return view;
}
}
public static class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1, null);
return view;
}
public void OnAttach(Activity Fragment1){
super.onAttach(Fragment1);
MediaPlayer mp = MediaPlayer.create(Fragment1.getApplication(), R.raw.s1);
mp.start();
}
}
//This fragment is supposed to start the MediaPlayer, but is doesn't
public static class Fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_2, null);
return view;
}
}
}
MediaPlayer need a context to instantiate. You are passing in a Fragment. You can create it at onAttach
http://developer.android.com/reference/android/app/Fragment.html#onAttach(android.app.Activity)
http://developer.android.com/guide/components/fragments.html#EventCallbacks
You put it in method onCreateView() if you want play sound when you start new fragment.
Media Player creation needs context but fragment don't have the context
For creating Media Player in a fragment you need to use getActivity() for getting the context
Example:
// creating media player in a fragment
happyBirthdaySong = MediaPlayer.create(getActivity(), R.raw.happy_birthday_female);
happyBirthdaySong.setLooping(true);
happyBirthdaySong.start();

Categories

Resources