I found the ViewPager in the android SDK and was messing around with it. Basically my final task is to create a youtube, facebook, and twitter feed all in one app, using the ViewPager and Fragments to scroll between the 3 categories. I'm having a bit of a hard time understanding house these work, more specifically, how to I add an element (Button) to a specific Fragment? Here's my code so far:
package com.ito.mindtrekkers;
import java.util.ArrayList;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
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.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("ShowToast")
//Brady Mahar
public class Main extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
ArrayList<String> tweetList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(1); //sets initial page to "Facebook"
new DownloadFilesTask().execute("weather" , null, null);
}
#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;
}
/**
* 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) {
switch (position) {
case 0:
return getString(R.string.title_youtube);
case 1:
return getString(R.string.title_facebook);
case 2:
return getString(R.string.title_twitter);
}
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() {
}
#SuppressLint("ShowToast")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create a new TextView and set its text to the fragment's section
// number argument value.
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return textView;
}
}
/**
* Class for handling NetworkOnMainThread
* Sends the command Asynchronously
* #author austinn
*
*/
private class DownloadFilesTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... command) {
Twitter twitter = new TwitterFactory().getInstance();
Query query = new Query("from:MindTrekkers");
query.setRpp(100);
try {
QueryResult result = twitter.search(query);
for(twitter4j.Tweet tweet : result.getTweets()) {
//Toast.makeText(getApplicationContext(), tweet.getText(), Toast.LENGTH_SHORT);
Log.v("Tweet", tweet.getText());
tweetList.add(tweet.getText());
}
} catch (TwitterException e) {
//Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_SHORT);
Log.v("Error", e+"");
}
return null;
}
protected void onProgressUpdate(Void... progress) {}
protected void onPostExecute(String result) {}
}
}
Implement your 3 Fragment categories (youtube, facebook, and twitter) in separate Fragment classes with a Singleton instance getter. Here's an Facebook Fragment example (note the onCreateView() inflates a fragment_facebook layout):
public class FaceBookFragment extends Fragment {
private static FaceBookFragment instance = null;
public static FaceBookFragment newInstance() {
if(instance == null) {
instance = new FaceBookFragment();
Bundle args = new Bundle();
instance.setArguments(args);
return instance;
}
return instance;
}
public FaceBookFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_facebook, container,
false);
...
return rootView;
}
}
Then in your FragmentPagerAdapter (located in the MainActivity of your code above), have the getItem() return the Fragment instance:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment frag = null;
switch (position) {
case 0:
frag = FaceBookFragment.newInstance();
break;
case 1:
frag = TwitterFragment.newInstance();
break;
case 2:
frag = YouTubeFragment.newInstance();
break;
}
return frag;
}
}
BONUS: Also, I know your code was experimental, but your tweetlist won't be accessible from any of your Fragments.
A Fragment is a new class object and can't access anything in the MainActivity directly unless you pass a reference to an object (the tweetlist) during construction (limiting), or get a 'final' on an object/variable if the Fragment code is under MainActivity (the list will never change from the Fragment's perspective). Maybe I didn't articulate this statement as well as other might, but tweetlist will not be accessible from your Fragment as it is.
There's a couple of solutions:
Move tweetlist to the Twitter Fragment and have it call the downloader. Then your TwitterFragment can construct and hold the list and update the UI as necessary. HOWEVER, consider the Fragment lifecycle (http://developer.android.com/guide/components/fragments.html), see the lifecycle section and diagram) The onDestroyView() method will be called when you swipe/flip over a couple of Fragments and back again. e.g. Android will not keep an indefinite number of Fragment alive and will destroy/re-create the view as needed. Don't try to update the Fragment's UI/layout objects from an AsyncTask. It's possible the Fragment might call onDestoryView() before your task completes. (you'll probably get NullPointerExceptions then) Instead have your AsyncTask only update Fragment scope variables (tweetlist) and have your onCreateView() use that same variable. (maybe synchronize the variable too)
Keep your major variable/objects/AsyncTask invoking code, all in the MainActivity, and add methods to access them from a Fragment, and have the Fragment getActivity() and cast it to MainActivity and call the method when needed:
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
ArrayList<String> tweetList = new ArrayList<String>();
...
public ArrayList<String> getTweetlist() {
return tweetlist;
}
...
}
public class TwitterFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_twitter, container, false);
...
ArrayList<String> tweetList = ((MainActivity)getActivity()).getTweetlist();
...
return rootView;
}
...
}
Let me try to explain, first use this FragmentPagerAdapter:
public class TestFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[] { "CATEGORIAS", "PRINCIPAL", "AS MELHORES", };
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar,
R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms,
};
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {Fragment f = null;
switch(position){
case 0:
{
f = new ArrayListFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 1:
{
f = new HomeFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 2:
{
f = new EndlessCustomView();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
default:
throw new IllegalArgumentException("not this many fragments: " + position);
}
return f;
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return TestFragmentAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
As you can see, ArrayListFragment, HomeFragment and EndlessCustomView is a class that extends Fragment, so for each of these classes inside onCreate() , You can setContentView(R.layout.your_layout);
Then you can add a button or whatever you want in this layout.
Related
I created a Tab Layout with Swipeable Views.
I'm trying to pass a string from fragment
to Fragment Thank you in Advance
Details_customer.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
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.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
public class Details_customer extends AppCompatActivity implements Cust_Details_basic.FragmentDataListener {
SharedPreferences login_pref, IP;
private ProgressDialog pDialog;//For Loading activity..
Bundle dataBundle;
/**
* The {#link PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_customer);
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);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onFragmentDataUpdated(Bundle dataBundle)
{
this.dataBundle=dataBundle;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
//getMenuInflater().inflate(R.menu.menu_details_customer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
login_pref = getSharedPreferences("Login Pref", MODE_PRIVATE);
SharedPreferences.Editor editor = login_pref.edit();
editor.putString("username", null);
Intent intent = new Intent(this, MainActivity.class);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Logout", Toast.LENGTH_SHORT).show();
/*editor.clear();*/
editor.commit();
finish();
break;
}
return super.onOptionsItemSelected(item);
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Details_customer Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
//deleted
/**
* 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) {
switch (position) {
case 0:
Cust_Details_basic cust_basic = new Cust_Details_basic();
cust_basic.setArguments(dataBundle);
return cust_basic;
case 1:
Cust_Details_address address = new Cust_Details_address();
address.setArguments(dataBundle);
return address;
/* case 2:
Cust_Details_last details_last = new Cust_Details_last();
return details_last;*/
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
/***
* new addition
***/
public void showFragment(String val) {
System.out.println(val);
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Basic Info";
case 1:
return "Address";
/* case 2:
return "Address";*/
}
return null;
}
}}
Cust_Details_basic.java Here is my Edittext i want to send the value to next fragment
public class Cust_Details_basic extends Fragment {
EditText finame;
private ProgressDialog pDialog;//For Loading activity..
public interface FragmentDataListener{
void onFragmentDataUpdated(Bundle dataBundle);
}
private FragmentDataListener mFragmentDataListener;
#Override
public void onAttach( Context context )
{
super.onAttach( context );
mFragmentDataListener=(FragmentDataListener)getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_customer_1, container, false);
finame = (EditText)view.findViewById(R.id.fname);
/**********************************************/
Bundle bundle = new Bundle();
bundle.putString("fname",finame.getText().toString());
mFragmentDataListener.onFragmentDataUpdated(bundle);
/*********************************************/
return view;
}}
Here is Cust_Details_address.java here i want Edittext value
public class Cust_Details_address extends Fragment implements View.OnClickListener{
Button btnsubmit;
String fname,firstname;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_customer_2, container, false);
Bundle bundle = this.getArguments();
if (bundle != null) {
firstname = bundle.getString("fname",fname);
Toast.makeText(getActivity().getApplicationContext(),"fname:"+firstname,Toast.LENGTH_SHORT).show();
Log.d("First Name:","=======>"+firstname);
}
else{
Toast.makeText(getActivity().getApplicationContext(),"Am Empty:",Toast.LENGTH_SHORT).show();
}
btnsubmit = (Button)view.findViewById(R.id.btnsubmit);
btnsubmit.setOnClickListener(this);
return view;
}}
In Cust_Details_address.java I Override the method like this
#Override
public void onStart(){
super.onStart();
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String firstname = ((EditText)getActivity().findViewById(R.id.fname)).getText().toString();
Toast.makeText(getActivity().getApplicationContext(),"Hi "+firstname ,Toast.LENGTH_SHORT).show();
} });
I got the result which i have accepted. Thank you so much 'Talha' for your needful help.
CallBacks(interface) and Bundles are recommended way but this is a quick solution:
YourActivity:
public void randomMethod(String val){
System.out.println(val);
}
Fragment1:
onClick(){
((YourActivity) getActivity()).randomMethod(yourString1);
}
Fragment2:
onClick(){
((YourActivity) getActivity()).randomMethod(yourString2);
}
You can call that method from any fragment of an activity and use the updated value.
In your activity define interface, bundle object, then call interface method of Activity instance with data from your fragment:
In Details_customer activity you do this,
public class Details_customer extends AppCompatActivity
implements Cust_Details_basic.FragmentDataListener {
SharedPreferences login_pref,IP;
private ProgressDialog pDialog;//For Loading activity..
Bundle dataBundle;
..... other code
// override method of interface
#override void onFragmentDataUpdated(Bundle dataBundle)
{
this.dataBundle=dataBundle;
}
...... other code
// in SectionsPagerAdapter adapter
#Override public Fragment getItem(int position) {
switch (position) {
case 0:
Cust_Details_basic cust_basic = new Cust_Details_basic();
cust_basic.setArguments(dataBundle); // remember to update
//bundle object as per requirement
return cust_basic;
case 1:
Cust_Details_address address = new Cust_Details_address();
address.setArguments(dataBundle);
return address;
/* case 2:
Cust_Details_last details_last = new Cust_Details_last();
return details_last;*/
}
return null;
}
In your Cus_Details_basic Fragment, declare interface:
public class Cust_Details_basic extends Fragment {
public interface FragmentDataListener{
void onFragmentDataUpdated(Bundle dataBundle);
}
private FragmentDataListener mFragmentDataListener;
// create fragment object and initialize it in onAttach()
#Override public void onAttach( Context context )
{
super.onAttach( context );
mFragmentDataListener=(FragmentDataListener)getActivity();
}
// then update your onCreate as:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_customer_1, container, false);
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString("fname",fname);
//fragment.setArguments(bundle);
mFragmentDataListener.onFragmentDataUpdated(bundle);
// this will update dataBundle object in your activity
return view;
}
This will call onFragmentDataUpdated() of your Details_customer class, which will update its dataBundle object, now whenever Viewpager changes, you should be able to setArguments() with this Bundle object, and eventually getArguments() in onCreate of that fragment will be able to retrieve data.
Useful links:
Communicating between Fragments.
How To Communicate Between Fragments and Activities in Android.
Since all the fragment are in view pager that means they share the same activity.So just put the value inside the intent and get it in any fragment of that view pager, no need to pass the data separately in bundle.
In your Cust_Details_basic Fragment (Save it like this)
getActivity().getIntent().putExtra("name",fname);
In Cust_Details_address Fragment (Get it like this )
String fname = getActivity().getIntent().getStringExtra("name");
In my MainActivity I have a list, and when an item is clicked, I go into my ScreenSlideActivity. This activity will produce a Fragment from another class I have called ScreenSlidePageFragment, and will produce a handful of Fragments for me when I swipe. I need the content in these Fragments to be unique depending on whichever item in the list I selected. Unfortunately I haven't been successful at this.
I've tried creating a set_all_data(string_data){} function inside the ScreenSlidePageFragment and the calling it/updating the textView before I create the Fragment, but I think I'm either getting a race condition with the new text, or I'm just doing it wrong and don't understand Fragments well enough.
ScreenSlideActivity
package com.example.dgzl.corvegas;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
/**
* Demonstrates a "screen-slide" animation using a {#link ViewPager}. Because {#link ViewPager}
* automatically plays such an animation when calling {#link ViewPager#setCurrentItem(int)}, there
* isn't any animation-specific code in this sample.
*
* <p>This sample shows a "next" button that advances the user to the next step in a wizard,
* animating the current screen out (to the left) and the next screen in (from the right). The
* reverse animation is played when the user presses the "previous" button.</p>
*
* #see ScreenSlidePageFragment
*/
public class ScreenSlideActivity extends android.support.v4.app.FragmentActivity {
/* The number of pages (wizard steps) to show in this demo.*/
private static final int NUM_PAGES = 3;
/* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.*/
private ViewPager mPager;
/* The pager adapter, which provides the pages to the view pager widget.*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
final String biz_data[] = in.getStringArrayExtra("biz_data");
set_fragment_data(biz_data);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
}
});
}
public void onFragClick (View view){
Toast.makeText(ScreenSlideActivity.this, "button", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_screen_slide, menu);
// enable 'prev' and 'next' when not on first node
menu.findItem(R.id.action_prev).setEnabled(mPager.getCurrentItem() > 0);
menu.findItem(R.id.action_next).setEnabled(mPager.getCurrentItem() < (NUM_PAGES-1));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 16908332:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html for more.
finish();
return true;
case R.id.action_prev:
// Go to the previous step in the wizard. If there is no previous step,
// setCurrentItem will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
return true;
case R.id.action_next:
// Advance to the next step in the wizard. If there is no next step, setCurrentItem
// will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A simple pager adapter that represents 5 {#link ScreenSlidePageFragment} objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
String test_data = "Soem data";
ScreenSlidePageFragment newFrag = new ScreenSlidePageFragment();
newFrag.set_all_data(test_data);
Fragment newFragment = newFrag.create(position);
return newFragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
public void set_fragment_data(String biz_data[]){
// title as business name
setTitle(biz_data[1]);
}
}
ScreenSlidePageFragment
package com.example.dgzl.corvegas;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* A fragment representing a single step in a wizard. The fragment shows a dummy title indicating
* the page number, along with some dummy text.
*
* <p>This class is used by the {#link } and {#link
* ScreenSlideActivity} samples.</p>
*/
public class ScreenSlidePageFragment extends android.support.v4.app.Fragment {
/**
* The argument key for the page number this fragment represents.
*/
public static final String ARG_PAGE = "page";
/**
* The fragment's page number, which is set to the argument value for {#link #ARG_PAGE}.
*/
private int mPageNumber;
public String[] todays_data, biz_data, special_data;
public String all_data = "hardcoded and not good";
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number.
*/
public static ScreenSlidePageFragment create(int pageNumber) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
Log.d("OnCreateView: ", "2");
return fragment;
}
public ScreenSlidePageFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView;
Log.d("OnCreateView: ", "1");
TextView tv;
switch(getPageNumber()){
case 0:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_today, container, false);
tv = (TextView)rootView.findViewById(R.id.today_frag_tv);
tv.setText(R.string.today_frag);
break;
case 1:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_business, container, false);
tv = (TextView)rootView.findViewById(R.id.biz_frag_tv);
tv.setText(all_data);
break;
case 2:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_specials, container, false);
tv = (TextView)rootView.findViewById(R.id.specials_frag_tv);
tv.setText(R.string.special_frag);
break;
default:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_today, container, false);
tv = (TextView)rootView.findViewById(R.id.today_frag_tv);
tv.setText(R.string.today_frag);
}
// Set the title view to show the page number.
// ((TextView) rootView.findViewById(android.R.id.text1)).setText(getString(R.string.title_template_step, mPageNumber + 1));
return rootView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return mPageNumber;
}
public void set_data(String[] todays_data, String[] biz_data, String[] special_data) {
this.todays_data = todays_data;
this.biz_data = biz_data;
this.special_data = special_data;
}
public void set_all_data(String all_data) {
this.all_data = all_data;
}
public void get_data() {
}
}
The problem is in getItem() method. You are creating a new ScreenSlidePageFragment, and after that, you call create() method that creates a new ScreenSlidePageFragment again. You need to call ScreenSlidePageFragment.create(position) in a static way.
#Override
public Fragment getItem(int position) {
String test_data = "Soem data";
ScreenSlidePageFragment newFrag = ScreenSlidePageFragment.create(position);
newFrag.set_all_data(test_data);
return newFragment;
}
I've created a new tabbed activity in Android Studio using the wizard (which oddly enough has some deprecated code - what's the deal with that?), but can't understand how to proceed with actually showing a fragment when pressing a tab. I found some examples such as this one or this one, but I keep thinking that if Google have created this default tabbed activity code as shown here, then it should be easy to proceed from there, no?
Here is the default Android Studio tabbed activity code:
package dk.gis34.borgertip.activity;
import java.util.Locale;
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.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
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 dk.gis34.borgertip.R;
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// 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.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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);
}
#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 PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#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 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;
}
}
}
And here is a default created fragment:
package dk.gis34.borgertip.fragment;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import dk.gis34.borgertip.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link ProfileFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link ProfileFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ProfileFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ProfileFragment.
*/
// TODO: Rename and change types and number of parameters
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public ProfileFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
Any ideas anyone?
In this part of the code you need to switch the position and return your fragments based on the position.
#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).
return PlaceholderFragment.newInstance(position + 1);
}
i want open new activity (List Activity) List.java under Tile Strip
how to use intent on the onCreateView
OR
How To add List On the onCreateView
main.java is Sample for Swipe View and Tile Strip on the Eclipse
Main.java :
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.TextView;
public class Main extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#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;
}
/**
* 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) {
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
case 2:
return getString(R.string.title_section3).toUpperCase();
}
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) {
// Create a new Intent and open New Activity
return ;
}
}
}
List.Java :
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class List extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
final String[] products = getResources().getStringArray(R.array.products);
// Binding Array to ListAdapter
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, products));
}
}
Your class List should extends ListFragment instead of ListActivity, then in your getItem from SectionsPagerAdapter, if position is 0 returns an istance of the class List else return an istance of DummyFragment
#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 = null;
if (position == 0) {
fragment = new List();
} else {
fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
}
return fragment;
}
your class List has to extends ListFragment
public class List extends ListFragment
I am trying to add a PreferenceFragment to a FragmentPagerAdapter.
My class extends FragmentActivity, I have tried FragmentTransaction, as shown below as well as trying to add to the container and can't seem to get anything to work. No errors are thrown, in fact nothing happens.
Main Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
activity_main.xml:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
</android.support.v4.view.ViewPager>
My Options menu selection:
android.app.FragmentManager fm;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
JJSettings settings = new JJSettings();
fm = getFragmentManager();
FragmentTransaction fragTrans = fm.beginTransaction();
// I also tried `replace()` here as well. Same 'nothing happens' result.
fragTrans.add(settings, "settings");
fragTrans.commit();
return true;
case R.id.menu_help:
menuHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
My settings Fragment:
public class JJSettings extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
My preference would be to stick with Fragments if possible, meaning I'd rather not extend PreferenceActivity or take the user to another Activity that calls the PreferenceFragment, if at all possible. I'm just hoping I missed something in my research.
Edit
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private int _count = 2;
public SectionsPagerAdapter(FragmentManager fm) { super(fm); }
#Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new JJMainFragment();
case 1:
return new JJPendingFragment();
default:
return null;
}
}
public void setCount(int count) { this._count = count; }
#Override
public int getCount() { return this._count; }
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.c_list).toUpperCase(Locale.ENGLISH);
case 1:
return getString(R.string.c_pending).toUpperCase(Locale.ENGLISH);
}
return null;
}
}
This answer led me to the solution of using the v13 support library, which includes a FragmentPagerAdapter that uses bona-fide android.app.Fragments so it can support the PreferenceFragment.
Assuming you use Eclipse and run the new app wizard with the "Scrollable Tabs + Swipe" Navigation (which gives you the v4 pager boilerplate), here are the modifications you need to make to upgrade to v13:
Delete "android-support-v4.jar" file from your libs folder
Copy "android-support-v13.jar" from SDK_PATH\extras\android\support\v13; if it's not there, use the SDK manager to install or update "Extras/Android Support Library"
Then, in the Java file:
Change FragmentPagerAdapter import from v4 to v13
Change FragmentActivity to a plain Activity
Change calls to getSupportFragmentManager to getFragmentManager
Import all necessary classes from android.app instead of android.support.v4
(Except: you still need to use the v4 ViewPager, but it's compatible)
I've copied the modified source below, verified on latest Jellybean.
MainActivity.java:
package com.example.pagerwithpreferencesfragment;
import java.util.Locale;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v13.app.FragmentPagerAdapter; // instead of v4.app...
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;
public class MainActivity extends Activity { // no longer FragmentActivity
// these comments are now out-of-date; v13, not v4
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getFragmentManager()); // instead of getSupportFragmentMangager
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#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;
}
/**
* 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) {
// this is just to show it compiles
if (position == 0) {
// you should really make this a public class elsewhere..
return new PreferenceFragment() {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_preferences);
}
};
}
// 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);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
}
settings_preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="my_category_key"
android:title="My Title">
<CheckBoxPreference
android:key="pref_key"
android:title="Title"
android:summary="Summary"
android:defaultValue="false"
/>
</PreferenceCategory>
</PreferenceScreen>
Documentation
I think you need to specify a container view id for the fragment transaction. Try giving it the id of your ViewPager. Or, put the ViewPager inside another container, give that an id, and use that.