This is one of my first apps. I want to know how I can detect what sliding tab the user is currently on. I know it in ViewPagerAdapter but I can't do anything because it's a fragment. How can I access this information?
MainActivity.java
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"Factorial", "Permutation", "Random"};
int Numboftabs = 3;
FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.fab_pressed);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.show(false);
//Animation FAB
Animation animation = AnimationUtils.loadAnimation(this, R.anim.simple_grow);
fab.startAnimation(animation);
}
#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) {
Toast.makeText(this, "Text", Toast.LENGTH_SHORT).show();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.simple_grow);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.startAnimation(animation);
return true;
}
return super.onOptionsItemSelected(item);
}
}
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
FactorialTab factorialTab = new FactorialTab();
return factorialTab;
} else if(position == 1) // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
PermutationTab permutationTab = new PermutationTab();
return permutationTab;
}
else {
RandomTab randomTab = new RandomTab();
return randomTab;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
RandomTab.java (one of the sliding tabs)
public class RandomTab extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_random, container, false);
return v;
}
}
Set an OnPageChangeListener to your ViewPager
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == WHATEVER) {
//do what you want
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Related
I'm a beginner. I am having a problem with Spinner. I'm using tabbed activity with fragments. When I add spinner in fragment main and add listener to it and when I run the app, it crashes, saying
( java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setOnItemSelectedListener(android.widget.AdapterView$OnItemSelectedListener)' on a null object reference)
I've checked everything and seems fine. I don't know what is the matter, please guys help me out. I really need to fix this bug, my Android Studio version is 2.1.2
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner)findViewById(R.id.spin);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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";
public PlaceholderFragment() {
}
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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* 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) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
I want to make a custom fragmentPagerAdapter. My application crashes and i've got cast exception. This is my code:
public class HomePagerAdapter extends FragmentPagerAdapter {
private static int[] ICONS = new int[] {
R.drawable.tab1drawable,
R.drawable.tab2drawable
};
public HomePagerAdapter(FragmentManager fm) {
super(fm);
}
// ...
#Override
public CharSequence getPageTitle(int position) {
return null;
}
#Override
public int getCount() {
return ICONS.length;
}
public int getDrawableId(int position) {
return ICONS[position];
}
#Override
public Fragment getItem(int position) {
return null;
}
}
And this is the exception :
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.androidsources.welcomescreen/com.androidsources.welcomescreen.MainActivity}:
java.lang.ClassCastException:
com.androidsources.welcomescreen.ViewPagerAdapter cannot be cast to
com.androidsources.welcomescreen.HomePagerAdapter
This is the line where crash occurs : tabs.setViewPager(pager); and this is the onCreate Method from MainActivity.cs
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}`
i am developing an android app which have a tab activity.in this activity there are four more tabs which is created by using Fragments.now i want to get the data from the fragment tabs in the main tab activity.i searched a lot but not find the exact answer.if any could solve this. below is my code
Main Tab Activity
public class TabedActivity extends ActionBarActivity {
// Declaring Your View and Variables
MobileServiceClient MSC;
MobileServiceTable MST;
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Basic","Education","Profession","Experiance"};
int Numboftabs =4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabed);
// Creating The Toolbar and setting it as the Toolbar for the activity
// toolbar = (Toolbar) findViewById(R.id.tool_bar);
//setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#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_tabed, 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.
item.getItemId();
switch (item.getItemId()) {
case R.id.action_settings:
goToHome();
return true;
case R.id.done:
Toast.makeText(this, "you select done", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
//noinspection SimplifiableIfStatement
}
public void goToHome(){
Intent gotohome=new Intent(this,MapsActivity.class);
startActivity(gotohome);
}
//the following function was added to update but not working
public static void settingValues(){
and the Tab activity
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.EditText;
import android.widget.Toast;
/**
* Created by hp1 on 21-01-2015.
*/
public class Tab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
EditText contactNumber= (EditText)v.findViewById(R.id.editTextcontact);
EditText address= (EditText)v.findViewById(R.id.editText2);
contactNumber.setHint("Your ContactNo Plz");
address.setHint("Your address Plz");
return v;
}
}
View Page Adapter class
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
Tab1 tab1 = new Tab1();
return tab1;
}
else if (position==1){
Tab2 tab2 = new Tab2();
return tab2;
}
else if (position==2){
Tab3 tab3 = new Tab3();
return tab3;
}
else // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
Tab4 tab4=new Tab4();
return tab4;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
Edit
In order get reference to your views you should declare that view(s) at class level for e.g
public class Tab1 extends Fragment {
EditTex address,contactNumber;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
contactNumber= (EditText)v.findViewById(R.id.editTextcontact);
address= (EditText)v.findViewById(R.id.editText2);
contactNumber.setHint("Your ContactNo Plz");
address.setHint("Your address Plz");
return v;
}
public String getData(){
return address.getText().toString();
}
}
First declare a global variable to maintain reference to currentPage being displayed
int currentPage = 0; // 0 - because initially 0th page is displayed.
You can get reference to your Fragment using the following method:
private static String makeFragmentName(int viewPagerId, int index) {
return "android:switcher:" + viewPagerId + ":" + index;
}
in the above viewPagerId is your ViewPager's id
You will need to keep a reference for the current page being displayed for this implement addOnPageChangeListener() on ViewPager and in onPageSelected() method update your currentPage variable.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Now in order to get data in onOptionsItemSelected() method you can do like below
// You will need to check for the index manually and get the reference of the current `Fragment` so a solution to this can be like
if(currentPage == 0){
Tab1 tab1 = (Tab1)getSupportFragmentManager().findFragmentByTag(makeFragmentName(R.id.your_view_pager,currentPage));
// always check for null
if(tab1 != null){
String data = tab1.getData();
}
}else if(currentPage == 1){
Tab2 tab2 = (Tab2)getSupportFragmentManager().findFragmentByTag(makeFragmentName(R.id.your_view_pager,currentPage));
if(tab2 != null){
String data = tab2.getData();
}
}
... so on
create method in your fragments to access the data for e.g
public String getData(){
String data = yourEditText.getText().toString();
return data;
}
similarly you can access other data as well, let me know if you require more details
this is nothing but the nested fragment basically fragment inside fragment(nesting) is not supported.your doing the same, Nested fragments are not currently supported. Trying to put a fragment within the UI of another fragment will result in undefined and likely broken behavior of the app..
I have searched for like three days for a solution for this. I have tried a lot of methods but I couldn't get it right. (Or maybe I am doing something wrong where).
So, what I am trying to do is change the Activity title to the current tab name, each time I change the tab, the activity title should change too.
So I have a MainActivity where I have 3 Tabs and 3 different fragments for the tabs. Here the MainActivity:
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
private ViewPager mPager;
private SlidingTabLayout mTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new CustomPagerAdapter(getSupportFragmentManager()));
mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
mTabs.setDistributeEvenly(true);
mTabs.setViewPager(mPager);
}
#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);
}
//Custom ViewPager for the tabs
class CustomPagerAdapter extends FragmentPagerAdapter {
String[] tabsTitles;
String vpPager;
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
tabsTitles = getResources().getStringArray(R.array.tabTitles);
}
#Override
public Fragment getItem(int position) {
//if (position == 0){
// news_fragment news_fragment = new news_fragment();
// return news_fragment;
//}
if (position == 1){
login_fragment login_fragment = new login_fragment();
return login_fragment;
}
else if (position == 2){
about_fragment about_fragment = new about_fragment();
return about_fragment;
}
else {
news_fragment news_fragment = new news_fragment();
return news_fragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
return tabsTitles[position];
}
#Override
public int getCount() {
return 3;
}
}
}
And I am using this SlidingTabLayout
Try this one :
viewpager
.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
actionBar.setTitle(tabsTitles[position]);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int pos) {
// TODO Auto-generated method stub
}
});
When you change activity. Firstlt onCreate method run. So in you onCreate get ActionBar and set its title.
EXAMPLE
ActionBar actionBar = getActionBar();
actionBar.setTitle("title");
Note : Change getActionBar() to getSupportActionBar() if you are using the support library for ActionBar.
Try this one too:
class CustomPagerAdapter extends FragmentPagerAdapter {
....
Toolbar toolbar;
public CustomPagerAdapter(FragmentManager fm, Toolbar toolbar) {
...
this.toolbar = toolbar;
}
#Override
public Fragment getItem(int position) {
toolbar.setTitle(getPageTitle(position));
...
}
...
}
Set a custom action bar in your activity by inflating some layout like(After Oncreate):
android.app.ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
bar.setDisplayShowHomeEnabled(false);
bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
bar.setCustomView(R.layout.homescreen_actionbar);
Take a TextView in your custom layout and in the onresume method of your fragment fetch its id using getactivity(), and set your title and iit will be working fine.
I have an activity that holds 2 fragments, one for list and one for detail. What I would like to do is, whenever a list item is clicked the related parameters will be sent to detail fragment. But I couldn't achieve it.
Here is activity:
public class ActivityMain extends ActionBarActivity{
/**
* 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.
*/
List<String> naviList = new ArrayList<String>();
ViewPager mViewPager;
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawer;
ListView navList;
DrawerAdapter naviAdapter;
private static final int GRAVITY = Gravity.LEFT;
private static final String jsonURL = "";
List<String> categories = new ArrayList<String>();
int check = -1, listCheck = 0;
Dialog d;
#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 activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//some methods (e.g. navi-drawer etc.)
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.medicalendar_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.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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:
return ListFragment.newInstance("FirstFragment, Default");
case 1:
return DetailFragment.newInstance("DetailFragment, Detail");
default:
return ListFragment.newInstance("FirstFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
private boolean version() {
if (Build.VERSION.SDK_INT > 11) {
return true;
} else {
return false;
}
}
My List Fragment:
public class ListFragment extends Fragment {
ListView list;
LazyAdapter adapter;
List<String> naviList = new ArrayList<String>();
RelativeLayout loading;
EventsParser parser;
List<Event> events = new ArrayList<Event>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_list, container, false);
parser = new EventsParser("");
events = parser.getITEMS();
list = (ListView) v.findViewById(R.id.list);
adapter = new LazyAdapter(getActivity(), events);
list.setAdapter(adapter);
return v;
}
public static ListFragment newInstance(String text) {
ListFragment f = new ListFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ViewPager vp = (ViewPager) getActivity().findViewById(R.id.pager);
//clicked item's data to pass next page.
vp.setCurrentItem(1);
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
My Detail Fragment:
public class DetailFragment extends Fragment {
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_detail, container, false);
ImageButton imageButton = (ImageButton) v.findViewById(R.id.d_map);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity().getApplicationContext(), "Navigating...", Toast.LENGTH_LONG).show();
}
});
return v;
}
public static DetailFragment newInstance(String text) {
DetailFragment f = new DetailFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
}
If you could help me I would be greatly appriciated.
Best,
Basically you don't need ViewPager for navigating from one fragment to another. This should be achieved with replacing fragments using FragmentTransaction class, that will allow you to pass parameters in transaction. http://developer.android.com/reference/android/app/FragmentTransaction.html
If you still need ViewPager, you should set tag for each fragment with
fragment.setTag("detail_fragment");
and than your onListItemClick method should look like this:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//get detail fragment instance by it's tag
DetailFragment detail = (DetailFragment) getActivity().getFragmentManager().findFragmentByTag("detail_fragment");
detail.setParam("data"); //you should define this method in your detail fragment
ViewPager vp = (ViewPager) getActivity().findViewById(R.id.pager);
//clicked item's data to pass next page.
vp.setCurrentItem(1);
}