I'm trying to create a Sign Up page, but if a user has already registered, then I want them to be able to swipe across to see the Sign In form instead.
Specifically, I'm trying to follow this Q&A: How do I use FragmentPagerAdapter to have tabs with different content? I've copied it all correctly, as far as I can see, but I'm having trouble with the part where the adapter instantiates the fragment.
In SignInActivity I have:
public class SignInActivity extends BaseActivity {
private TabLayout mTabLayout;
SignInPagerAdapter mSignInPagerAdapter;
public List<String> fragments = new Vector<String>();
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
// Set up tabs and fragments
mTabLayout = (TabLayout) findViewById(R.id.tabs);
mTabLayout.addTab(mTabLayout.newTab().setText(R.string.reg));
mTabLayout.addTab(mTabLayout.newTab().setText(R.string.sign_in));
fragments.add(RegisterObjectFragment.class.getName());
fragments.add(SignInObjectFragment.class.getName());
mSignInPagerAdapter =
new SignInPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSignInPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
}
private class SignInPagerAdapter extends FragmentPagerAdapter {
List<String> fragmentsA;
SignInPagerAdapter(FragmentManager fm) {
super(fm);
fragmentsA = fragments;
}
#Override
public Fragment getItem(int i) {
return Fragment.instantiate(getApplicationContext(), fragmentsA.get(i));
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch(position) {
case 0:
return getString(R.string.register);
case 1:
return getString(R.string.sign_in);
}
return null;
}
}
The layout activity_sign_in.xml contains this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/colorBg"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</android.support.v4.view.ViewPager>
</android.support.constraint.ConstraintLayout>
Then RegisterObjectFragment and SignInObjectFragment both extend Fragment and each have a corresponding layout.
The problem seems to be with this function in SignInActivity:
public Fragment getItem(int i) {
return Fragment.instantiate(getApplicationContext(), fragmentsA.get(i));
}
At that point it's crashing out with the error:
RegisterObjectFragment cannot be cast to android.support.v4.app.Fragment
It seems to be expecting a regular Fragment, but is getting the RegisterObjectFragment instead. Every example I can find has something along these lines, though - the function is supposed to return a Fragment, but instead is returning a user-generated extended Fragment. I've tried using some of the variations I've come across, but hit the same issue every time - it refuses to accept anything other than a Fragment.
Can anyone see where I'm going wrong?
Never mind - the problem was that the Fragment classes (RegisterObjectFragment and SignInObjectFragment) were extending android.app.Fragment, while the main class was using android.support.v4.app.Fragment.
When I changed them all to support.v4, it started to work!
Leaving this here in case anyone else gets stuck on the same thing.
Related
In my fragment I have material search bar with navigation button(humbugger).
How can I call Navigation Drawer which is in main activity with that humbugger button in my fragment
Do not get how to handle it inside DictionaryFragment
MainActivity:
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
drawer,
R.string.nav_open_drawer,
R.string.nav_close_drawer){
};
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
DictionaryFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
materialSearchBar = (MaterialSearchBar) RootView.findViewById(R.id.search_bar);
...
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onButtonClicked(int buttonCode) {
//***HOW TO HANDLE IT HERE?***
//switch (buttonCode) {
// case MaterialSearchBar.BUTTON_NAVIGATION:
// drawer.openDrawer(Gravity.START);
// break;}
}
});
//return RootView;
}
layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/searchBarDividerColor"
tools:context="com.hfad.catchat.DictionaryFragment">
<com.mancj.materialsearchbar.MaterialSearchBar
android:id="#+id/search_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:mt_hint="Search"
app:mt_navIconEnabled="true"
app:mt_speechMode="false" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
</android.support.v7.widget.RecyclerView>
</LinearLayout>
This is what you can try where you want to toggle navigation drawer in your fragment, this way you will have to write a method in activity to do whatever you want to do from your fragment, be sure it is a public method:
((MainActivity)getContext()).toggleDrawer();
in your MainActivity:
public void toggleDrawer(){
//do your stuff
}
Other way is callback aka interface (the preferred one), pass that as a parameter in fragment's constructor and consume that where you want to change drawer's state. Like inside your activity:
Callback callback = new Callback(){
#Override
public void onDrawerStateChanged(){
//do your stuff
}};
new DictionaryFragment(callback);
And inside your fragment you will have to write a constructor to accept that callback and save in a local variable :
public DictionaryFragment() {
}
#SuppressLint("ValidFragment")
public DictionaryFragment(Callback callback) {
this.callback = callback;
}
And use it like :
callback.onDrawerStateChanged();
You can also pass parameters to MainActivity both ways.
I have a PreferenceActivity with a custom layout to keep a static header on top of all the items. I followed this thread to set this up:
Adding a header to a PreferenceActivity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/myCustomImageView"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:src="#mipmap/ic_launcher" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/myCustomImageView" />
</RelativeLayout>
and here is my Activity snippet:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this makes a static header
setContentView(R.layout.preferences_layout);
// register as a listener
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.preference_headers, target);
}
yet, when I tap on an item it should spawn a fragment as my xml specifies:
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<header
android:fragment="ui.UserPreferences"
android:summary="#string/preferences_activity_user_settings_summary"
android:title="#string/preferences_activity_user_settings_title" />
more items....
However, it does not. Instead, it crashes saying:
java.lang.IllegalArgumentException: No view found for id 0x1020463 (android:id/prefs) for fragment UserPreferences
I looked at a bunch of threads like the one below, but they did not help.
Android PreferenceFragment No view found for id for fragment
However if I just commented out the custom layout, the code works and the fragment shows up correctly. This works, in other words:
public class Preferences extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this works: By commenting out the custom header, the exception goes away
//setContentView(R.layout.preferences_layout);
// register as a listener
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
}
I believe the fragment manager is not able to find the id because the listview is now nested inside a relativelayout. Yet, I have no idea how to fix this.
here's a bit of item fragment, however I don't think this is the problem:
public class UserPreferences extends PreferenceFragment implements
Preference.OnPreferenceChangeListener,
Preference.OnPreferenceClickListener,
SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Load the preferences from an XML resource */
addPreferencesFromResource(R.xml.user_settings);
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
more stuff...
Any help is greatly appreciated.
thank you.
I am at ends wit with my code. I can not get a fragment to display after it is called by another fragment (via Activity). I read the Android Developer guide and many SO's related topic on Fragment/FragmentPagerAdapter/FragmentTransactions and could not resolve my issue. This one would have been an obvious solution Is it possible to remove a fragment without replacing it by another fragment
I have an activity class that will host a fragment based on the tab selected. These fragments are dynamically created by the FragmentPagerAdapter based on user's selection of the tab. In the first tab, it creates FragmentA (ListFragment) which consists of a list of items. When a user clicks on any of the item, it should display another fragment with that item's details but to much of my dismay (and eyes burning), all it does is print out my log in logcat. Please see my code. Perhaps, I am staring at it too long and/or just don't know enough of android to see what's going on. I suspect it has to do with this line: fragTransaction.replace(R.id.curriculumParent, fragC); Now I know this would work if the 1st parameter was a fragment container in the activity's layout file was define but since it is not done statically, I don't know what to put there except for the calling FragmentB's layout file.
Thanks in advance!
MainActivity.java
public class MainActivity extends FragmentActivity implements
FragmentB.OnColorSelectedListener {
private static final String TAG = "MainActivity";
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
FragmentManager fm = getSupportFragmentManager();
adapter = new MyPagerAdapter(fm);
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
getResources().getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
}
...
...
...
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "FragmentB", "2ndTabFragment", "3rdTabFragment" };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position)
{
return TITLES[position];
}
#Override
public int getCount()
{
return TITLES.length;
}
#Override
public Fragment getItem(int position)
{
Fragment fragment = null;
switch (position) {
case 0:
fragment = Fragment.instantiate(getBaseContext(), FragmentB.class.getName());
break;
case 1:
fragment = Fragment.instantiate(getBaseContext(), SecondTabFragment.class.getName());
break;
case 2:
fragment = Fragment.instantiate(getBaseContext(), ThirdTabFragment.class.getName());
break;
}
return fragment;
}
}
#Override
public void onColorLevelSelected(int position)
{
Log.i(TAG, "Got Here!");
FragmentC fragC = new FragmentC();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragTransaction = fm.beginTransaction();
**fragTransaction.replace(R.id.curriculumParent, fragC);**
fragTransaction.addToBackStack(null);
fragTransaction.commit();
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
android:background="#drawable/background_tabs" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".MainActivity" />
</RelativeLayout>
FragmentB.java
public class FragmentB extends ListFragment{
OnColorSelectedListener mCallback;
private String[] colorLevel = new String[]{
"Yellow",
"Orange",
"Green",
"Blue",
"pink",
"Black"
};
private int[] colorImages = new int[]{
R.drawable.yellow,
R.drawable.orange,
R.drawable.green,
R.drawable.blue,
R.drawable.pink,
R.drawable.black
};
public interface OnColorSelectedListener{
public void onItemLevelSelected(int position);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
List<HashMap<String, String>> colorList = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < 6; i++){
HashMap<String, String> colorMap = new HashMap<String, String>();
colorMap.put("lvl", colorLevel[i]);
colorMap.put("img", Integer.toString(colorImages[i]));
colorList.add(colorMap);
}
String[] from = {"img", "lvl"};
int[] to = {R.id.colorLevelImg, R.id.colorLevelTxt};
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b ,from, to);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
mCallback = (OnColorSelectedListener) activity;
}catch(ClassCastException e){
throw new ClassCastException(activity.toString()
+ " must implement OnColorSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int pos, long id){
Toast.makeText(getActivity(), "selected color :" + colorLevel[pos],
Toast.LENGTH_LONG).show();
mCallback.onColorLevelSelected(pos);
}
}
fragment_b.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
**android:id="#+id/curriculumParent"**
...
...
android:background="#FEFDFB">
<ImageView
android:id="#+id/colorLevelImg"
...
android:paddingBottom="10dp" />
<LinearLayout
...
android:orientation="vertical" >
<TextView
android:id="#+id/colorLevelTxt"
...
android:textSize="25sp" />
</LinearLayout>
</LinearLayout>
FragmentC.java
public class FragmentC extends Fragment{
public static final String TAG = "Fragment C";
public FragmentC(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
Log.i(TAG, "HI");
return inflater.inflate(R.layout.fragment_c, container, false);
}
}
fragment_c.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFCC00" >
<TextView
android:id="#+id/editText1"
...
android:layout_margin="16dp"
android:text="This is the C Fragment that will replace the B Fragment" >
</TextView>
</RelativeLayout>
I noticed FragmentB.java does not explicitly point to any layout file to inflate. In case you don't know,
ListFragment has a default layout that consists of a single list view
, documented # ListFragment. So you're still fine if you only want a simple ListView, but maybe NOT. But then you have code that references another layout to FragmentB:
new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b...
Note: R.layout.fragment_b is the layout specified for the ArrayAdapter only! Not for the fragment. But this is normal and may be fine.
In MainActivity, onColorLevelSelected():
fragTransaction.replace(R.id.curriculumParent,...
Note:
I think this replaces the layout only for the adapter and not the fragment.
Perhaps you want to inflate a layout file containing a ListView, and use that for the fragments.
Your problem is basically the layout, work with that.
EDIT:
Code suggestion:
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_x
public void onColorLevelSelected(int position)
FragmentC fragX = new FragmentX();
...
fragTransaction.replace(R.id.curriculumParent, fragX);
Notes:
Notice I am using an example of an arbitrary FragmentX. The Adapter and the replace() matches each other.
I understand this code change is somewhat considerable. Since I said it, here is a new code suggestion:
public void onListItemClick(ListView l, View v, int pos, long id){
Toast.makeText(getActivity(), "selected color :" + colorLevel[pos], Toast.LENGTH_LONG).show();
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b ,from, to);
...
setListAdapter(adapter);
...
mCallback.onColorLevelSelected(pos); }
Note: This code change is made only to be simpler, my attempt. The idea is when the user click on a row in ListView, you know which layout and fragment is used. Hopefully that makes code less complicated.
I am trying to create tabs inside a fragment. I manage to create tab inside the fragment, but now I want to load different fragment for each tab (fragment1.class and fragment2.class).
Can anybody please suggest how can i load each fragment to their respective tabs?
Below is my main fragment that is holding the tabs.
Thanks a lot!
public class BusFragment extends Fragment {
private TabHost mTabHost;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_bus, container, false);
mTabHost = (TabHost) rootView.findViewById(R.id.tabHost);
mTabHost.setup();
TabHost.TabSpec spec = mTabHost.newTabSpec("tag");
spec.setIndicator("Fragment1");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
spec = mTabHost.newTabSpec("tag1");
spec.setIndicator("Fragment2");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
spec = mTabHost.newTabSpec("tag2");
spec.setIndicator("Fragment3");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
return rootView;
}
}
Hello If you want to load the fragment inside the fragment android provide the Child Fragment Manager instead of ordinary fragment manager. I had the same issue I had the fragment inside that tab when click on tab want to load the different fragments. see the below steps hope will help you.
Step 1. See I have StatisticsFragment with it layout fragment_statistics.
public class StatisticsFragment extends Fragment {
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_statistics,container, false);
mTabHost = (FragmentTabHost) rootView.findViewById(R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(),R.id.tabFrameLayout);
mTabHost.addTab(mTabHost.newTabSpec("WEEK").setIndicator(buildTabLayout(EnumStatistics.WEEKLY)),WeekFragment_.class, null);
mTabHost.addTab(mTabHost.newTabSpec("ALL").setIndicator(buildTabLayout(EnumStatistics.ALL)),DetailedFragment_.class, null);
mTabHost.getTabWidget().getChildAt(0).setOnClickListener(new WeekTabClick());
mTabHost.getTabWidget().getChildAt(1).setOnClickListener(new AllTabClick());
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
private View buildTabLayout(EnumStatistics enumStatistics) {
View tab;
if (enumStatistics == EnumStatistics.WEEKLY) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_week_layout, null);
} else if (enumStatistics == EnumStatistics.MONTHLY) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_month_layout, null);
} else if (enumStatistics == EnumStatistics.YEAR) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_year_layout, null);
} else {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_detailed_layout, null);
}
return tab;
}
public class WeekTabClick implements View.OnClickListener {
#Override
public void onClick(View v) {
mTabHost.getTabWidget().focusCurrentTab(0);
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.tabFrameLayout, WeekFragment_.instantiate(getActivity(), WeekFragment_.class.getName()));
ft.addToBackStack(null);
ft.commit();
}
}
public class AllTabClick implements View.OnClickListener {
#Override
public void onClick(View v) {
mTabHost.getTabWidget().focusCurrentTab(1);
FragmentTransaction ft = getChildFragmentManager()
.beginTransaction();
ft.replace(R.id.tabFrameLayout, DetailedFragment_.instantiate(
getActivity(), DetailedFragment_.class.getName()));
ft.addToBackStack(null);
ft.commit();
}
}
}
In above buildTabLayout function intent to build the custom layout of tab widget you can put simple text or image that you want to show inside the tab widget.
Steps 2. fragment_statistics.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:relaxis="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.app.FragmentTabHost
android:id="#+id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/croutonview"
android:gravity="center" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
/>
<FrameLayout
android:id="#+id/tabFrameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
</RelativeLayout>
As you see in the above inside the layout tabFrameLayout we load the all child fragment Programmaticly.
Let me know if you have any question and doubt. thank you
The activity is called from another activity delivering a string array, which needs to be displayed in a fragment of the target activity.
MainActivity (string array) -> Result2Activity: Tab1 should display string index0, Tab2 should display string index1 etc.
I followed a similar problem here:
Access Fragment View from Activity's onCreate
My problem is right now that the onActivityCreated method is never called in the Result2Activity.
I am also not sure if this method is the right way to address the fragment:
getSupportFragmentManager().findFragmentByTag("Out1");
What is the best way to achieve that ?
Result2Activity:
public class Result2Activity 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;
public List<String> fragments = new Vector<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result2_activity);
// 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));
}
Log.d("DEBUG","1: onCreate finished");
}
public void onActivityCreated (Bundle savedInstanceState) {
Log.d("DEBUG","2: onActivityCreated finished");
//super.onActivityCreated(savedInstanceState);
// retrieve data from MainActivity
Intent intent = getIntent();
String message[] = intent.getStringArrayExtra(MainActivity.OUTPUT);
//send data to fragment Out1Fragment
Out1Fragment set_out1 =
(Out1Fragment)
getSupportFragmentManager().findFragmentByTag("Out1");
set_out1.settext(message[0]);
}
#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) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
fragments.add(Out1Fragment.class.getName());
fragments.add(Out2Fragment.class.getName());
fragments.add(Out3Fragment.class.getName());
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Out1Fragment();
break;
case 1:
fragment = new Out2Fragment();
break;
case 2:
fragment = new Out3Fragment();
break;
}
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.out_section1).toUpperCase(l);
case 1:
return getString(R.string.out_section2).toUpperCase(l);
case 2:
return getString(R.string.out_section3).toUpperCase(l);
}
return null;
}
}
}
Out1Fragment:
public class Out1Fragment extends Fragment {
private static TextView textview;
public Out1Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View dataView = inflater.inflate(R.layout.out1_fragment, container,
false);
textview = (TextView) dataView.findViewById(R.id.outPut1);
return dataView;
}
public void settext(String text)
{
textview.setText(text);
}
}
XML Resource:
result2_activity.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="dd.testing.finance.Result2Activity" />
out1_fragment.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ScrollView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:tag="Out1"
tools:context="dd.testing.finance.Result2Activity$Out1Fragment" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:id="#+id/outPut1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:textSize="16sp" />
</LinearLayout>
</ScrollView>
Not really sure if this was the right way, but at least it does exaclty what I needed.
In the Out1Fragment.class added the onActivityCreated method:
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
settext(((Result2Activity)getActivity()).getOutput1());
}
From there calling the added method getOutput1 in the Result2Activity:
public String getOutput1 () {
// retrieve data from MainActivity
Intent intent = getIntent();
String message[] = intent.getStringArrayExtra(MainActivity.OUTPUT);
return message[0];
}