How to include another Tab ViewPager in another Fragment? - android

So I have successfully implemented a Tab viewpager on a fragment inside the navigation drawer. Now my question is, how do you include another set of tabs in another separate fragment in a single PagerAdapter (Using this pager: you can swipe on any tabs which the tabhost doesnt).
Heres my code for the "other" fragment:
AttendeesFragment.java:
package com.example.guitarista.citem;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class AttendeesFragment extends Fragment {
public AttendeesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
getActivity().setTitle("Attendees");
View v = inflater.inflate(R.layout.fragment_attendees, container, false);
TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("All"));
tabLayout.addTab(tabLayout.newTab().setText("VIP"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); //check gravity center
final ViewPager viewPager = (ViewPager) v.findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getFragmentManager(), tabLayout.getTabCount());
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) {
}
});
return v;
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and this is my code for PagerAdapter.java
package com.example.guitarista.citem;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by smdojt on 1/11/2017.
*/
public class PagerAdapter extends FragmentStatePagerAdapter{
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabInternationalFragment tab1 = new TabInternationalFragment();
return tab1;
case 1:
TabLocalFragment tab2 = new TabLocalFragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
Notice that there are already tabs in the public fragment (i.e. TabsInternationalFragment, TabsLocalFragment) and now I want to include another tabs on other fragments (i.e. AllTab,VIPTab)

You have to create a different PagerAdapter this time, and I think this is just a temporary solution.

Related

Add ViewPager in Fragment in Android

I have two fragments: FirstFragment and SecondFragment. FirstFragment contains ViewPager, which has three pages (three fragments). In the onCreate of activty, I add FirstFragment to main layout, and three pages show normally.
Problem is: when I replace FirstFragment by SecondFragment, and then comeback FirstFragment three pages disappear. Then I scroll ViewPager forward and backward, pages show but only first and third pages show, second page disappear.
Here FirstFragment:
package com.example.bkmsx.afragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstFragment extends Fragment {
ViewPager mViewPager;
static MainActivity mainActivity;
public static FirstFragment newInstance(MainActivity activity){
mainActivity = activity;
return new FirstFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_fragment, null);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(mainActivity.getSupportFragmentManager());
mViewPager.setAdapter(adapter);
return view;
}
private class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
String text = "";
switch (position) {
case 0: text = "First Page";
break;
case 1: text = "Second Page";
break;
case 2: text = "Third Page";
break;
}
return TextFragment.newInstance(mainActivity, text);
}
#Override
public int getCount() {
return 3;
}
}
}
SecondFragment:
package com.example.bkmsx.afragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SecondFragment extends Fragment {
static MainActivity mainActivity;
public static SecondFragment newInstance(MainActivity activity) {
mainActivity = activity;
return new SecondFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
TextView textView = new TextView(mainActivity);
textView.setText("New Fragment");
return textView;
}
}
Any suggestion? Thanks in advance.
In FirstFragment , Use this code and try
public View view; // declare view as global variable
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
if(view == null){
view = inflater.inflate(R.layout.first_fragment, null);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(mainActivity.getSupportFragmentManager());
mViewPager.setAdapter(adapter);
}
return view;
}
As Divyesh comment has good suggestion there is also need to add
mViewPager.setOffscreenPageLimit(3);
use ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager() ); instead of mainActivity.getSupportFragmentManager()
Try this code Hope it helps
final ViewPager viewPager = (ViewPager) findViewById(R.id.container);
final PagerAdapter adapter = new PaginationAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOffscreenPageLimit(3);
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) {
}
});

Populating Custom ListView in a Fragment

I have two activities, the main activity invokes a navigation drawer and one of the drawer items invokes another activity(event_activity) containing a Swipeable Tabbed layout. Each tab is a fragment invoked by the the event_activity. Now i want to populate custom ListViews to each fragment from a json data.
I tried using THIS tutorial, but its meant to be used with an activity, so got error while doing it with my fragment.
So, is there any way to populate the fragments using custom listviews?
Tabbed layout
This is my event_activity
package com.explore.sargam.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.explore.sargam.R;
import android.support.design.widget.TabLayout;
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 java.util.ArrayList;
import java.util.List;
import com.explore.sargam.OneFragment;
import com.explore.sargam.ThreeFragment;
import com.explore.sargam.TwoFragment;
import com.explore.sargam.FourFragment;
public class ResultActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Day 1");
adapter.addFragment(new TwoFragment(), "Day 2");
adapter.addFragment(new ThreeFragment(),"Day 3");
adapter.addFragment(new FourFragment(), "Day 4");
viewPager.setAdapter(adapter);
}
#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_result, 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);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
And this is my Fragment code
package com.explore.sargam;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class TwoFragment extends Fragment{
private static final String TAG = TwoFragment.class.getSimpleName();
public TwoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_two, container, false);
}
}

How to set onclick listener for tabView with listed items and move to a new Activity

Here I created a simple Tablayout with some options under it. When clicked on particular item the application should open another activity containing the particular class. Could Some one please help how to write the code for item onclick listener .Here I am attaching the code of my TabLayout java class and my versionModel java class with xml included. I am also attaching the screenshot of the app. So as in the screenshot when i click on the Topwear , page containing Topwear should open.
TabAnimationActivity.java
import android.annotation.SuppressLint;
import android.content.Intent;
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.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.suleiman.material.R;
import com.suleiman.material.adapter.SimpleRecyclerAdapter;
import com.suleiman.material.model.VersionModel;
import java.util.ArrayList;
import java.util.List;
public class TabAnimationActivity extends AppCompatActivity {
SimpleRecyclerAdapter adapter;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_animation);
final Toolbar toolbar = (Toolbar) findViewById(R.id.tabanim_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ViewPager viewPager = (ViewPager) findViewById(R.id.tabanim_viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabanim_tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
showToast("One");
break;
case 1:
showToast("Two");
break;
case 2:
showToast("Three");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment(getResources().getColor(R.color.accent_material_light)), "Men");
adapter.addFrag(new DummyFragment(getResources().getColor(R.color.ripple_material_light)), "Women");
adapter.addFrag(new DummyFragment(getResources().getColor(R.color.button_material_dark)), "Kids");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tab_switch, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_switch:
Intent intent = new Intent(TabAnimationActivity.this, TabsHeaderActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public static class DummyFragment extends Fragment {
int color;
SimpleRecyclerAdapter adapter;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
List<String> list = new ArrayList<String>();
for (int i = 0; i < VersionModel.data.length; i++) {
list.add(VersionModel.data[i]);
}
adapter = new SimpleRecyclerAdapter(list);
recyclerView.setAdapter(adapter);
return view;
}
}
}
VersionModel.java
public class VersionModel {
public String name;
public static final String[] data = {"Topwear", "Bottomwear", "Footwear",
"Sports wear", "Innerwear &Sleepwear", "SmartWearables",
"Watches", "Accessories", "PersonalGrooming", "T-Shirts"};
VersionModel(String name){
this.name=name;
}
}
dummy_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dummyfrag_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_material_light">
<android.support.v7.widget.RecyclerView
android:id="#+id/dummyfrag_scrollableview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
I hope This may give you an idea on Recyclerview OnItemClick.
RecyclerView recyclerView = (RecyclerView)v.findViewById(R.id.dummyfrag_scrollableview);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(llm);
recyclerView.setHasFixedSize(true); // to improve performance
recyclerView.setAdapter(new YourRecylerAdapter());
recyclerView.addOnItemTouchListener( new RecyclerClickListener(getContext(), new RecyclerClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(getActivity(),
YourDetailedActivity.class);
startActivity(intent);
}}));
return v;

Calling Custom ListView Adapter from Fragment Class Main Activity

I've written a few listView activities, as a proof of concept for myself that I could do it. Now, I'm having trouble loading a listView activity into a single tab for an app with multiple tabs, that allows both swiping and tab selection for navigation. I get the error "The constructor ListView_Adapter(MainActivity.DummySectionFragment) is undefined" when I try to write the code for it. I'm a beginner, and I've lurked pretty hard here for the past few days. Any help is appreciated.
TL;DR : I'm a n00b, and I can't figure out this problem.
My Custom List Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomListViewAdapter extends ArrayAdapter<String> {
public CustomListViewAdapter (Context c) {
super(c, R.layout.list_cell);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ListView_Text holder = null;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_cell, parent, false);
holder = new ListView_Text(row);
row.setTag(holder);
}
else
{
holder = (ListView_Text) row.getTag();
}
holder.populateFrom(getItem(position));
return row;
}
static class ListView_Text {
private TextView cell_name = null;
ListView_Text(View row) {
cell_name = (TextView) row.findViewById(R.id.list_cell_name);
}
void populateFrom(String index) {
cell_name.setText(index);
}
}
}
My Main Activity
import java.util.Locale;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import com.example.twigglebeta2.ListView_Adapter;
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.app.NavUtils;
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.ListView;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private static ListView_Adapter listViewAdapter;
private ListView listView;
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create adapter
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Switch tab selection to match current page when swiped
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// Create a tab for each 'count' in the activity from getCount()
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
Tab thisTab = actionBar.newTab();
thisTab.setText(mSectionsPagerAdapter.getPageTitle(i));
thisTab.setTabListener(this);
actionBar.addTab(thisTab);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
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 DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
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;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,container, false);
switch(getArguments().getInt(ARG_SECTION_NUMBER)){
case 1:
//The constructor ListView_Adapter(MainActivity.DummySectionFragment) is undefined
listViewAdapter = new ListView_Adapter(this);
ListView listView = (ListView) rootView.findViewById(R.id.listView1);
for (int i=0;i<20;i++)
{
listViewAdapter.add("this Index : "+i);
}
return listView;
}
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
Instead of listViewAdapter = new ListView_Adapter(this);, you should instead try listViewAdapter = new ListView_Adapter(getActivity().getBaseContext());
The Issue is that you are passing a Fragment to the constructor, and not an Activity context.

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