Android getting the Fixed Tab, PageViewer to load different fragments - java

I'm new to software development and java as a whole, I've been trying for days now to get the default template android gives for fixed tabbed Navigation with pageviewer. Regardless of what I try I can't seem to get it to load anything but the first fragment. all the other onClick tabs events in the Emulator load the very same first fragment defined in the template, sliding the pager has the same effect.
I've tried modifying my code several times till the point where there are little runtime errors, but I still can't get it to load other fragments through the Tabs.
I'd appreciate any help with this.
here's my code.
My projects a Native tablet EHR App
package com.example.medictouch;
import java.util.Locale;
import com.example.medictouch.MedicTouchActivity.encountersFragment;
import com.example.medictouch.MedicTouchActivity.patient_chartFragment;
import com.example.medictouch.MedicTouchActivity.billingFragment;
import com.example.medictouch.MedicTouchActivity.medicationsFragment;
import com.example.medictouch.MedicTouchActivity.treatmentsFragment;
import com.example.medictouch.MedicTouchActivity.laboratoryFragment;
import com.example.medictouch.MedicTouchActivity.imagingFragment;
import com.example.medictouch.MedicTouchActivity.doctors_notesFragment;
import com.example.medictouch.MedicTouchActivity.departmentsFragment;
import android.app.ActionBar;
import android.app.FragmentTransaction;
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 MedicTouchActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* 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.medictouch);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
// 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);
// 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 void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new encountersFragment();
Fragment fragment1 = new patient_chartFragment();
Fragment fragment2 = new billingFragment();
Fragment fragment3 = new medicationsFragment();
Fragment fragment4 = new treatmentsFragment();
Fragment fragment5 = new laboratoryFragment();
Fragment fragment6 = new imagingFragment();
Fragment fragment7 = new doctors_notesFragment();
Fragment fragment8 = new departmentsFragment();
return fragment;
}
#Override
public int getCount() {
// Show 6 total pages.
return 10;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toLowerCase();
case 1:
return getString(R.string.title_section2).toLowerCase();
case 2:
return getString(R.string.title_section3).toLowerCase();
case 3:
return getString(R.string.title_section4).toLowerCase();
case 4:
return getString(R.string.title_section5).toLowerCase();
case 5:
return getString(R.string.title_section6).toLowerCase();
case 6:
return getString(R.string.title_section7).toLowerCase();
case 7:
return getString(R.string.title_section8).toLowerCase();
case 8:
return getString(R.string.title_section9).toLowerCase();
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public class encountersFragment extends Fragment {
private final int title_section1 = 0;
public final int ARG_SECTION_NUMBER = title_section1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.encounters,
container, false);
return rootView;
}
}
public class patient_chartFragment extends Fragment {
private final int title_section2 = 1;
public final int ARG_SECTION_NUMBER = title_section2;
public patient_chartFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.patient_chart,
container, false);
return rootView;
}
}
public class billingFragment extends Fragment {
private final int title_section3 = 2;
public final int ARG_SECTION_NUMBER = title_section3;
public billingFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.billing,
container, false);
return rootView;
}
}
public class medicationsFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 3;
public medicationsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.medications,
container, false);
return rootView;
}
}
public class treatmentsFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 4;
public treatmentsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.treatments,
container, false);
return rootView;
}
}
public class laboratoryFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 5;
public laboratoryFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.labs,
container, false);
return rootView;
}
}
public class imagingFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 6;
public imagingFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.imaging,
container, false);
return rootView;
}
}
public class doctors_notesFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 7;
public doctors_notesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.doctors_notes,
container, false);
return rootView;
}
}
public class departmentsFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 8;
public departmentsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.departments,
container, false);
return rootView;
}
}
}

You need to use switch..case.. block in getItem(int position) method. Use below code.
#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;
switch (position) {
case 0:
fragment = new encountersFragment();
break;
case 1:
fragment = new patient_chartFragment();
break;
case 2:
fragment = new billingFragment();
break;
case 3:
fragment = new medicationsFragment();
break;
case 4:
fragment = new treatmentsFragment();
break;
case 5:
fragment = new laboratoryFragment();
break;
case 6:
fragment = new imagingFragment();
break;
case 7:
fragment = new doctors_notesFragment();
break;
case 8:
fragment = new departmentsFragment();
break;
default:
break;
}
return fragment;
}
Edit:
I found this error in your code(may have more errors). You are using AutoCompletTextView in xml change it to AutoCompleteTextView
08-16 21:53:46.247: E/AndroidRuntime(4768): Caused by:
java.lang.ClassNotFoundException: Didn't find class "android.view.AutoCompletTextView" on
path: DexPathList[[zip file "/data/app/com.example.medictouch-
2.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.medictouch-2, /system/lib]]

Related

Tabbed Activity Page Title not showing

This is what I was trying to do, The "Tab One" "Tab Two" as my Tabbed Page Title. Ignore the Toolbar
I created an app that uses tabbed activity, I used the preset tabbed activity in android studio and modified it to my use. But I'm having a problem in showing the tabbed title. I'm working only on 2 tabs for now but i'm planning to add more as I progress.
Here is the codes for my Tabbed Activity Class
public class StudLearnTab extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
String key;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabbed_content);
// 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);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Bundle bundle = new Bundle();
bundle.putString("keys",key);
fragment_tabbed_content tab1 = new fragment_tabbed_content();
tab1.setArguments(bundle);
return tab1;
case 1:
fragment_tabbed_activity tab2 = new fragment_tabbed_activity();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Content";
case 1:
return "Try Yourself";
}
return null;
}
}
}
My Fragments only contains the constructor and createview but I'll included it here for reference. Both fragments are almost the same.
public class fragment_tabbed_activity extends Fragment {
public fragment_tabbed_activity() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabbed_activity, container, false);
return rootView;
}
}

How do I use android fragment java class?

I set up a fragment which looks like this:
The EditText("5") has the id et_input. Now I want to interact with my EditText but it doesn't work.
MainActivity.java
public class MainActivity extends AppCompatActivity {
/**
* 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
getSupportActionBar().hide();
}
/**
* 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() {
}
/**
* 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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
switch (getArguments().getInt(ARG_SECTION_NUMBER) - 1) {
case 1:
return inflater.inflate(R.layout.fragment_roman_numbers, container, false);
case 2:
return inflater.inflate(R.layout.fragment_binary_numbers, container, false);
default:
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
}
/**
* 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) {
if(position == 0) {
return main.newInstance();
} else if(position == 1) {
return roman_numbers.newInstance();
} else if(position == 2) {
return binary_numbers.newInstance();
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.fragment_home);
case 1:
return getString(R.string.fragment_roman_numbers);
case 2:
return getString(R.string.fragment_binary_numbers);
}
return null;
}
}
}
binary_numbers.java
public class binary_numbers extends Fragment {
public binary_numbers() {
// Required empty public constructor
}
public static binary_numbers newInstance() {
binary_numbers fragment = new binary_numbers();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
}
roman_numbers.java and main.java look exactly the same except for binary_numbers being replaced with their names.
fragement_binary_numbers.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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"
tools:context="com.ngtnttnmnt.xtool.MainActivity$PlaceholderFragment">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/et_input"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:hint="#string/input_hint"
android:gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/tv_output"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="40dp"
android:gravity="center" />
fragement_roman_numbers.xml looks exactly the same and fragement_main.xml has two TextView's
Should be
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
EDIT:
As I said, you're showing a different fragment. In reality, you are showing the PlaceholderFragment created within your SectionsPagerAdapter, which just selects the binary_number layout when it's inflated, but you're not actually showing a binary_numbers fragment.
Your code should be the following:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
getSupportActionBar().hide();
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return home.newInstance();
} else if(position == 1) {
return roman_numbers.newInstance();
} else if(position == 2) {
return binary_numbers.newInstance();
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.fragment_home);
case 1:
return getString(R.string.fragment_roman_numbers);
case 2:
return getString(R.string.fragment_binary_numbers);
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
}
}
Please note the complete removal of the PlaceholderFragment class, because you won't need it, ever.
EDIT: also add
public class home extends Fragment {
public static home newInstance() {
return new home();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
EDIT:
Also modify your binary_numbers class like so
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.ngtnttnmnt.xtool.InputFilterMinMax;
import com.ngtnttnmnt.xtool.R;
public class binary_numbers extends Fragment {
public binary_numbers() {
// Required empty public constructor
}
public static binary_numbers newInstance() {
binary_numbers fragment = new binary_numbers();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private PlaceholderFragment mPlaceholderFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(mPlaceholderFragment == null){
mPlaceholderFragment = PlaceholderFragment.newInstance(position + 1);
}
return mPlaceholderFragment;
}
It should be like this

Android Swipe View help needed

I have a swipe Activity, with 2 swipe pages, I added the content for the first page and on the second page the content is duplicated, how can I set different content to the second page in my swipe view?
public class ListItemClicked extends ActionBarActivity {
static Bundle extras;
SectionsPagerAdapter mSectionsPagerAdapter;
static ImageLoader imageLoader;
static DisplayImageOptions options;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_clicked);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
extras = getIntent().getExtras();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section4).toUpperCase(l);
case 1:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "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_list_item_clicked, container, false);
TextView pDate = (TextView) rootView.findViewById(R.id.textView);
pDate.setText( extras.getString("pdate") );
TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
ptitle.setText(extras.getString("pname"));
TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
pnText.setText( extras.getString("pText"));
return rootView;
}
}
}
Android Developers site really has very good explanation of ViewPager. You should check it out:
http://developer.android.com/training/animation/screen-slide.html
Here is an example I wrote:
activity_screen_slide.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Java Code:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
...
public class ScreenSlidePagerActivity extends FragmentActivity {
private static final int NUM_PAGES = 2;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
//Create these fragments with your preferable names
switch (position) {
case 0:
return new ScreenSlidePageFragment();
case 1:
return new ScreenSlidePageFragment2();
default:
break;
}
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
And here is one of your views that should look like it where fragment_ screen_slide_page is one of your layouts:
import android.support.v4.app.Fragment;
...
public class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
return rootView;
}
}
You should really read the android developers site for further details.
You can return different fragments like this:
#Override
public Fragment getItem(int position) {
if (position == 0) {
return PlaceholderFragment.newInstance(position + 1);
} else {
return anotherFragment.newInstance();
}
}
If you want to use the same Fragment, you can change the content depending on the position you are passing to the fragment.

Android SwipeViews + TitleStrip + ListView

My new project consists of a Navigation Drawer with 6 fragments ( Audi / BMW / KIA... car brads ). I want each Fragment to have 2 other fragments ( Models, which will have a ListView with car models and the second fragment, called Pictures, it's obvious what that contains). I don't like tabs, that's why I chose TitleStrip with swipe navigation between the fragments.
BMW.java
public class BMW extends Fragment {
CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(com.zenyt.R.layout.fragment_bmw, container, false);
mCollectionPagerAdapter = new CollectionPagerAdapter(
getFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActivity().getActionBar();
// Specify that the Home button should show an "Up" caret, indicating
// that touching the
// button will take the user one step up in the application's hierarchy.
actionBar.setDisplayHomeAsUpEnabled(true);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) rootView.findViewById(R.id.bmw_pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
return rootView;
}
public class CollectionPagerAdapter extends FragmentStatePagerAdapter {
final int NUM_ITEMS = 2; // number of tabs
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public CharSequence getPageTitle(int position) {
String tabLabel = null;
switch (position) {
case 0:
tabLabel = getString(R.string.label1);
break;
case 1:
tabLabel = getString(R.string.label2);
break;
}
return tabLabel;
}
}
public static class TabFragment extends Fragment {
public static final String ARG_OBJECT = "object";
private ListView myListView;
private String[] strListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
switch (position) {
case 0:
tabLayout = R.layout.models;
break;
case 1:
tabLayout = R.layout.pictures;
break;
}
View rootView = inflater.inflate(tabLayout, container, false);
return rootView;
}
}
}
In TabFragment, I want fragments instead of layouts (models and pictures). How can I do that?
models.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#android:color/black"
>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView2" />
</RelativeLayout>
Models.java
public class Models extends Fragment {
private ListView myListView;
private String[] strListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(com.zenyt.R.layout.models, container, false);
myListView = (ListView) rootView.findViewById(com.zenyt.R.id.listView2);
strListView = getResources().getStringArray(com.zenyt.R.array.bmw_list_data);
ArrayAdapter<String> objAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, strListView);
myListView.setAdapter(objAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
return rootView;
}
}
Seems that I solved it by myself. All I had to do was to change a bit the PagerAdapter, like this:
public class CollectionPagerAdapter extends FragmentStatePagerAdapter {
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0:
return new Bmw1();
case 1:
return new Bmw2();
default:
break;
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
String tabLabel = null;
switch (position) {
case 0:
tabLabel = getString(R.string.label1);
break;
case 1:
tabLabel = getString(R.string.label2);
break;
}
return tabLabel;
}
}

Create static class instance in android

I saw a code here. Also shown below:
I'm in bit confused in Fragment fragment = new DemoObjectFragment(); where public static class DemoObjectFragment extends Fragment is a static class. So how we can call fragment.setArguments(args);
public class CollectionDemoActivity extends FragmentActivity {
// When requested, this adapter returns a DemoObjectFragment,
// representing an object in the collection.
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
mDemoCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
}
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
I created a base class for using fragments. I don't know if that will work for you. In a base class you can put information that's the same for all fragments. In my case a want to use a shared view model in all fragments. So I put the shared view model in the base class :
/**
* base class for the application
*/
public abstract class BaseFragment extends Fragment {
// use shared view model for exchanging information between fragments.
SharedViewModel sharedViewModel;
/**
* this function creates view and shared view model
* #param inflater - inflater creates the view
* #param container - container with views
* #param savedInstanceState - for saving state
* #return - return view
*/
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
// call base class first
super.onCreateView(inflater, container, savedInstanceState);
// then create view
View fragView = inflater.inflate(getFragment(), container, false);
// get shared view model.
sharedViewModel = new
ViewModelProvider(requireActivity()).get(SharedViewModel.class);
// inject fragment depended code
createView(fragView);
// return created view
return fragView;
}
/**
* get fragment
* (override in fragments and return xml layout name)
*/
protected abstract int getFragment();
/**
* inject fragment depended code while creating the view
* (override in fragments with fragment depended code)
*/
protected abstract void createView(View fragView);
}

Categories