How i can move data from DB to my ViewPager? - android

Class with DB and realization of Adapter.
public class MainActivity extends AppCompatActivity {//implements
View.OnClickListener{
ArrayList<String> titles = new ArrayList<>();
ArrayAdapter arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
titles);
listView.setAdapter(arrayAdapter);
try {
SQLiteDatabase myDatabase = this.openOrCreateDatabase("Places",
MODE_PRIVATE, null);
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS places (name VARCHAR,
time INT(2), solo INT(1), id INTEGER PRIMARY KEY)");
myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES
('One', 23, 1)");
myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES
('Two', 24, 2)");
myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES
('Three', 22, 1)");
myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES
('Four', 02, 2)");
Cursor c = myDatabase.rawQuery("SELECT * FROM places WHERE solo =
1", null);
int nameIndex = c.getColumnIndex("name");
int timeIndex = c.getColumnIndex("time");
int soloIndex = c.getColumnIndex("solo");
int idIndex = c.getColumnIndex("id");
if (c.moveToFirst()) {
titles.clear();
do {
titles.add(c.getString(nameIndex));
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
}
c.close();
myDatabase.execSQL("DELETE FROM places");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Class with realization Fragment and PagerAdapter:
public class MyGallery extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_gallery);
// 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);
}
/**
* 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) {
View rootView = inflater.inflate(R.layout.fragment_my_gallery,
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;
}
}
}
I'm trying to move a field named "name" (nameIndex) from the database to the viewpager screen. I can not move cursor values ​​to a class with the creation of a Fragment. I read about the method of entering data into the List and moved from there, the number of the required position to the FragmentPager, but it did not quite work out. Can someone know a simple and elegant way to solve this problem?

When you instantiate your FragmentPagerAdapter, pass an ArrayList to adapter constructor as argument
mSectionsPagerAdapter = new
SectionsPagerAdapter(getSupportFragmentManager(), titles);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
In your adapter use a reference, and get string from array, such like
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private ArrayList<String> strings;
public SectionsPagerAdapter(FragmentManager fm, ArrayList<String> strings) {
super(fm);
this.strings = strings;
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1, strings.get(position + 1));
}
#Override
public int getCount() {
return strings.size();
}
}
And finally, in your Fragment class, pass it as argument, and get as a global variable from onCreate method
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";
private String title;
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String title) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putString("key", title);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
title = getArguments().getString("key");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my_gallery,
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;
}
}
Note. For better control on your code, if you have limited number of fragment, you should make an all cases using switch statement. Calling position + 1 in you adapter may throw nullpointerexception, when an index of your array will be exceeded. You can start any postion using viewPager.setCurrentItem(position);, example of FragmentPagerAdapter with switch statement should looks like
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return PlaceholderFragment.newInstance(position, strings.get(position));
case 1:
return PlaceholderFragment.newInstance(position, strings.get(position));
case 2:
return PlaceholderFragment.newInstance(position, strings.get(position));
default:
return something...
}
}

Related

Moving EditText input from an Activity to a Fragment of a swipe view

This is the MainActivity upon launch. The user puts in a number then clicks the button and the Intent brings them to a swipe view with the number they entered.
public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
continueButton = (Button) findViewById(R.id.ContinueButton);
NumberET = (EditText) findViewById(R.id.etTotalAmount);
continueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
number = NumberET.getText().toString();
if (number.equals("")) {
Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
} else {
Bundle bundle = new Bundle();
bundle.putString("AMOUNT_KEY", number);
FixedCosts fragment = new FixedCosts();
fragment.setArguments(bundle);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.container, fragment).commit();
Intent intent = new Intent(MainActivity.this, FragmentActivity.class);
intent.putExtra("NUMBER", number);
startActivity(intent);
}
}
});
}
In the fragment, I would like to set the text of a textview to display that number. I cannot get this number to send from this Activity class to the Fragment. How can I fix this?
Fragment:
ublic class FixedCosts extends Fragment {
String amount;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fixed_costs_fragment, container, false);
amount = this.getArguments().getString("AMOUNT_KEY");
TextView TitletextView = (TextView) view.findViewById(R.id.amountTitle);
TitletextView.setText(amount);
return view;}}
Here is the FragmentActivity that sets the swipe view:
public class FragmentActivity extends AppCompatActivity {
public static final String MY_CUSTOM_FRAGMENT_KEY = "I_GOT_THE_KEYS";
String MoneyAmount;
/**
* 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.fragment);
/*MoneyAmount = getIntent().getExtras().getString("AmountMoney");*/
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);
}
private Fragment createCustomFragment(){
Bundle bundle = new Bundle();
bundle.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);
PlaceholderFragment placeholderFragment = new PlaceholderFragment();
placeholderFragment.setArguments(bundle);
return placeholderFragment;
}
#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_, 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() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String MoneyAmount) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);
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);
Bundle bundle = getArguments();
/*String amount = bundle.getString(MY_CUSTOM_FRAGMENT_KEY);
TextView TitletextView = (TextView) FixedCosts.class.findViewById(R.id.amountTitle);
TitletextView.setText(amount);*/
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) {
switch (position){
case 0:
FixedCosts fixedCosts = new FixedCosts();
return fixedCosts;
}
return PlaceholderFragment.newInstance(position + 1, MoneyAmount);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Fixed Costs";
case 1:
return "Long term investments";
case 2:
return "SECTION 3";
}
return null;
}
}
}
Remove activity start code in continueButton.setOnClickListener listener and add view container in same layout for parent activity not in fragment activity:
public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
continueButton = (Button) findViewById(R.id.ContinueButton);
NumberET = (EditText) findViewById(R.id.etTotalAmount);
continueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
number = NumberET.getText().toString();
if (amount.equals("")) {
Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
} else {
Bundle bundle = new Bundle();
bundle.putString("AMOUNT_KEY", number);
FixedCosts fragment = new FixedCosts();
fragment.setArguments(bundle);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.container, fragment).commit();
}
}
});
}
Hope it will help you.
I fixed the issue by saving the value to SharedPreferences.
In the MainActivity.class:
SharedPreferences saveAmount = getSharedPreferences("MyPrefs", 0);
final SharedPreferences.Editor editor = saveAmount.edit();
editor.putString("AMOUNT", amount);
editor.commit();
In the Fragment class:
SharedPreferences sharedPrefs = this.getActivity().getSharedPreferences("MyPrefs", 0);
String amount = (sharedPrefs.getString("AMOUNT", "Ummmmm"));

Android creating dynamic fragments with dynamic data using gridview and realm DB?

I want to load category and products like the image shown:
frag
/**
* 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) {
Category ctID = mSubCategory.get(position);
int id = ctID.getCategory_id();
return PlaceholderFragment.newInstance(getBaseContext(),id);
}
#Override
public int getCount() {
// Set number of fragments to be created
if(SubCategoriesCount == 0) {
Category ct;
ct = mSubCategory.get(0);
if (ct != null)
return 1;
}
return SubCategoriesCount;
}
}
Creating Fragment using newInstance with different Data.
PlaceholderFragment.java
public class PlaceholderFragment extends Fragment {
private static final String FragmentCategoryID = "CategoryID";
private static Context cTx;
private static String catName;
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(Context ctx, int id){
PlaceholderFragment fragment = new PlaceholderFragment();
cTx = ctx;
Log.d("New Fragment Created ", ":" + id );
Bundle args = new Bundle();
args.putInt(FragmentCategoryID, id);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_category_products_view, container, false);
RealmResults<Product> ProductList;
ProductList = GetProducts(getArguments().getInt(FragmentCategoryID));
Log.d("Fragment Arguments", "" + getArguments().getInt(FragmentCategoryID));
GridView gv = (GridView) rootView.findViewById(R.id.gridViewFrg);
gv.setAdapter(new AdapterRealmProduct(getActivity(), R.layout.grid_view_main, ProductList, true));
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(FragmentCategoryID))+ ":::"+catName);
return rootView;
}
private RealmResults<Product> GetProducts(int CategoryID){
RealmConfiguration realmConfigs;
realmConfigs = new RealmConfiguration.Builder(getActivity()).build();
Realm realmtm = Realm.getInstance(realmConfigs);
Category camt = realmtm.where(Category.class).equalTo("category_id", CategoryID).findFirst();
catName = camt.getName();
RealmResults<Product> results = realmtm.where(Product.class).equalTo("category_id", CategoryID).findAll();
try{
if(results != null && results.isValid()) {
return results;
}
}catch (IllegalStateException e){
e.printStackTrace();
}finally {
//realmtm.close();
}
return results;
}
}
It loads creates multiple fragments as value of SubCategoriesCount. But data in all fragments is same. Means All gridViews on all fragments have same grid data.
textView.setText(getString(R.string.section_format, getArguments().getInt(FragmentCategoryID))+ ":::"+catName);
CategoryName and ID displays.. but data does not change...
it might be Realm data. how to handle realm handle in different activitis.
there was repeated data in realm. So there is no problem in above code. I didn't notice what is coming to realm database.

How to capture the active section or tab of the swipeable tabs in android?

I'm using swipeable tabs as part of an activity with a total of 3 sections. I'm providing the right and left arrows to navigate to the other sections of the swipe-view.
I want my left arrow to disappear when I'm at the leftmost section and my right-arrow to disappear when I'm at the rightmost section.
Here's what I'm trying rightnow, but not getting the desired result:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
static Button rightButton;
static Button leftButton;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rightButton = (Button)findViewById(R.id.buttonRight);
leftButton = (Button)findViewById(R.id.buttonLeft);
// 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);
}
/**
* 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;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
// Returns a new instance of this fragment for the given section number.
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
String text = instructions(sectionNumber);
textView.setText(text);
return rootView;
}
private String instructions(int sectionNumber) {
if (sectionNumber == 1) {
leftButton.setVisibility(View.INVISIBLE);
rightButton.setVisibility(View.VISIBLE);
Log.i("Welcome"," to section 1");
return "All questions are mandatory. Each question carries 1 mark. There is no negative marking";
}
else if(sectionNumber == 2) {
leftButton.setVisibility(View.VISIBLE);
rightButton.setVisibility(View.VISIBLE);
Log.i("Welcome", " to section 2");
return "Color the bubble besides the option you think is best for the answer.";
}
else {
leftButton.setVisibility(View.VISIBLE);
rightButton.setVisibility(View.INVISIBLE);
Log.i("Welcome", " to section 3");
return "Click on the skip button above to start the test. Timer will start as soon as you'll click that button!";
}
}
}
}
As you can see in the method instructions, I tried using logs to see what's happening only to find that I never get the "Welcome to section 2" part even after swiping through the tabs multiple times. Although, the texts related to a given section are returned correctly. What am I missing here?
The problem is that you returned a new fragment in getItem
Do it like this:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragments.add(PlaceholderFragment.newInstance(1));
mFragments.add(PlaceholderFragment.newInstance(2));
mFragments.add(PlaceholderFragment.newInstance(3));
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
}
Also change the Buttons to the fragment_main layout "not" in activity_main and use it like this.
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private Button rightButton;
private Button leftButton;
// Returns a new instance of this fragment for the given section number.
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
rightButton = (Button)rootView.findViewById(R.id.buttonRight);
leftButton = (Button)rootView.findViewById(R.id.buttonLeft);
int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
String text = instructions(sectionNumber);
textView.setText(text);
return rootView;
}
EDIT if you want to know the cuurent page you have to implement this.
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.i("Welcome", "page "+ position+1);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Also add the following line so that the system will create your fragment only once:
mViewPager.setOffscreenPageLimit(3);
The issue you had is that you're getting the position that the system created now not the current page.

How to hand different Strings to dynamically created Fragments using ViewPager?

I can't seem to find a way to give different text to a dynamically created fragment for my pageviewer-supoorted application. I've came to a point of my codding where I got stuck. For my application I want to have 400-500 dynamically created fragments, where you can horizontally slide thru them and every content of the fragment to be the same (repeating the same fragment) and the only different thing to be the text on them.
Here's where I got stuck at my codding :
package com.example.testarearg;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/ private String mText; // display this text in your fragment
public static Fragment getInstance(String text) {
Fragment f = new Fragment();
Bundle args = new Bundle();
args.putString("text", text);
f.setArguments(args);
return f;
}
public void onCreate(Bundle state) {
super.onCreate(state);
setmText(getArguments().getString("text"));
// rest of your code
}
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
}
}
You need to create your own custom Fragment:
import android.support.v4.app.Fragment;
public class YourFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_fragment_layout, container, false);
TextView tv = (TextView) v.findViewById(R.id.yourtextview);
tv.setText(getArguments().getString("text"));
return v;
}
public static YourFragment newInstance(String text) {
YourFragment f = new YourFragment();
Bundle b = new Bundle();
b.putString("text", text);
f.setArguments(b);
return f;
}
}
And then modify your adapter. The basic idea is that the adapter
contains the Strings that you want to display and the getItem(...)
method will choose the text.
public class MyPagerAdapter extends FragmentPagerAdapter {
private String [] strings;
public MyPagerAdapter(FragmentManager fm, String [] stringstodisplay) {
super(fm);
this.strings = stringstodisplay;
}
#Override
public Fragment getItem(int pos) {
return YourFragment.newInstance(strings[pos]);
}
#Override
public int getCount() {
return 500; // or strings.length to be save
}
}
From your Activity, you hand over the String array containing the different strings to the adapter.
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the content that your fragments will display
String [] strings = new String[500];
for(int i = 0; i < 500; i++) {
strings[i] = "This is Fragment " + i;
}
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), strings));
}
}

3.0 above android version for scrollable swipe tabs, how to add different screen for different tab

I am a beginner to android applications,I working around tab+swipe application,
my main class is like belove. please help me out.
public class MainScreenViewActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
private static String list_display_data1 = "item#sec1";
private static String list_display_data2 = "item#sec2";
private static String list_display_data3 = "item#sec3";
private static View rootView;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen_view);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
/*mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen_view, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = null;
fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(
R.layout.fragment_main_screen_view_dummy, container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
dummyTextView.setVisibility(View.INVISIBLE);
if(dummyTextView.getVisibility() == View.VISIBLE){
ListView sessionList = (ListView) rootView.findViewById(R.id.session_list);
initListView(getActivity(), sessionList, list_display_data1, 30, android.R.layout.simple_list_item_1);
}
else{
Log.d("", "");
}
//ListView sessionList = (ListView) rootView.findViewById(R.id.session_list);
//initListView(getActivity(), sessionList, list_display_data1, 30, android.R.layout.simple_list_item_1);
return rootView;
}
}
public static void initListView(Context context, ListView listView,String prefix, int numItems, int layout ){
// By using setAdpater method in listview we an add string array in list.
String[] arr = new String[numItems];
for(int i = 0; i< arr.length; i++){
arr[i] = prefix + (i +1);
}
listView.setAdapter(new ArrayAdapter<String>(context, layout, arr));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Context context = view.getContext();
String msg = "item[" + position + "]= " + parent.getItemIdAtPosition(position);
Toast.makeText(context, msg, 1000).show();
System.out.println(msg);
}
});
}
}
in onCreateView of dummySectionFragment how to add different list view. I just able to work on visibility of view.
You should Add Fragments to your viewpager for different page for different Tabs.

Categories

Resources