Better way to populate/manage views in android? - android

I used to program in iOS language where every UIView class has its own UIViewController class to manage/populate the view itself. I'm trying now to write a simple android app that parse a JSONArray from url and then populate four views but I don't know how to implement a class for every view and pass them the strings parameters to populate them. Could you tell me what is the best way to implement the logic of the app? I have the new project with swipable-tabs then I have to use fragments. Are these fragments the same as the UIView in iOS? Help me please.
I did this, I would like to know if it is correct. I created a new Project with Blank activity and "Scrollable Tabs + Swipe" as Navigation type.
My main activity:
public class MyMainActvity extends FragmentActivity {
private static String url = "http://www.myurl.it";
static JSONObject jObj = null;
/**
* 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_activity);
new JSONParse().execute();
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_activity, 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.
switch (position) {
case 0:
{
HomeSection homeFrag= new HomeSection();
homeFrag.newInstance(jObj);
return homeFrag;
}
case 1:
{
ServiceSection servFrag= new ServiceSection();
servFrag.newInstance(jObj);
return servFrag;
}
case 2:
{
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
case 3:
{
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
}
return null;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#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);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_dummy, container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
private class JSONParse extends AsyncTask<String, String, JSONArray> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MyMainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONArray doInBackground(String... args) {
JSONParser jParser= new JSONParser();
JSONArray json =jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONArray json) {
pDialog.dismiss();
Log.d("JSONARRAY:", json.toString());
try {
JSONObject json_data = json.getJSONObject(0);
jObj= json_data;
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
catch(JSONException exception) {
Log.e("ERROR", exception.getMessage());
}
}
}
}
And this is one one my subclassed Fragments:
public class HomeSection extends Fragment {
JSONObject _jObj;
public HomeSection(){}
public void newInstance(JSONObject jObj) {
Bundle args = new Bundle();
_jObj= jObj;
try{
String content= _jObj.getString("descrizione");
args.putString("description", content);
}
catch(JSONException exception){
Log.e("ERROR JSON HOME", exception.getMessage());
}
// Put any other arguments
this.setArguments(args);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_dummy, container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
try {
dummyTextView.setText(_jObj.getString("descrizione"));
}
catch(JSONException exception){
Log.e("ERROR JSON HOME", exception.getMessage());
}
return rootView;
}
}
It works but I would like if it is a correct way to populate the views in my app. Then I didn't know if in the HomeSection class, the Bundle that I created in the "newIstance" method is effectively necessary because I set my text in the view within the method onCreateView. Could you help me please? Thanks

No. Fragments are not the equivalent of UIView. The equivalent of UIView is the Android View class. However, this is not used directly in most cases.
Unlike iOS, Android doesn't use a pure MVC pattern. It uses something more like a MVP pattern (See MVC pattern on Android and Which design patterns are used on Android?). Here, the Activity acts as the main View container and is the main entry point for the application.
Basically, you can use one of the subclasses of the View class such as TextView, ImageView etc and put them inside an Activity or a Fragment.
The Activity/Fragment will inflate your views (make objects out of them after parsing the XML) and show them to the user. The user can then interact with the views and these touch events will be routed by the Activity/Fragment to the respective views or will consumed by the Activity/Fragment itself depending on your logic.
I suggest you go through this excellent Android Bootcamp tutorial series which will really help you learn all the basics along with the 'Android way' of doing things.

Related

Impossible to add or remove pages dinamically from ViewPager Android Activity

I've read all stackOverflow answers regarding this topic, and any of them worked for me, or I couldn't make it myself.
As you can see in the code below, I added the default ViewPager Activity from Android Studio, and now I need to add new pages or remove existing pages from the corresponding buttons.
So, the activity is loading correctly and gets the correct number of pages, and I can also change the information in each of them successfully. As you can see, the app is connected to Firebase and I get from there the total number of pages (dogs) that my activity should have, this is working well.
Now, How can I add a new page, move to that page, and update the adapter and total number of pages?
Same for removing, How can I remove the current page, then move to another one and update the adapter with no problems?
I'm getting totally crazy with this, spent the whole day with diffeent solutions I found in stackoverflow, but could not make it. I'm now confused about when to use the "notifyDataSetChanged()", if it is a good idea override the "getItemPosition" or not, etc.
I would appreciate if someone could finally help me adapting the answer to my project, it's the default ViewPager just modified small parts to try to fix it, but don't know what else I can do.
Thank you in advance and sorry for my english.
Note: Some functions like "updateIntValueFromCurrentUser()" are declared in MainActivity but working, they are related to firebase queries etc so I'm not focusing on this.
public class DummyViewPagerActivity extends MainActivity {
/**
* 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 static ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dummy_view_pager);
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);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
//Creating menu bar
#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_dummy_view_pager, menu);
return true;
}
//Creating the two buttons to save and delete the images
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.add:
updateIntValueFromCurrentUser("dogs_number", person.getDogs_number()+1);
return true;
case R.id.edit:
return true;
case R.id.delete:
updateIntValueFromCurrentUser("dogs_number", person.getDogs_number()-1);
return true;
default:
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) {
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 = null;
try {
rootView = inflater.inflate(R.layout.fragment_dummy_view_pager, container, false);
TextView dogName = (TextView) rootView.findViewById(R.id.dog_name);
dogName.setText(allDogs.get((getArguments().getInt(ARG_SECTION_NUMBER)) - 1).getName());
} catch (Exception e) {
Log.e("RaisedException()", e.getMessage());
}
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
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 getItemPosition(Object object) {
// POSITION_NONE makes it possible to reload the PagerAdapter
return POSITION_NONE;
}
#Override
public int getCount() {
// Show x total pages.
return person.getDogs_number();
}
#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;
}
}
}
Adding/Removing items from FragmentViewPager is a bit tricky thing to do:
Try using this adapter and let me know is it working for you.
public class CodebaseFragmentPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<Fragment>();
public CodebaseFragmentPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
public void removeItem(int position){
mFragmentList.remove(position == 0 ? 0 : position - 1);
this.notifyDataSetChanged();
}
public void clearAllItems(){
mFragmentList.clear();
this.notifyDataSetChanged();
}
public void updateItem(int position, Fragment fragment){
mFragmentList.set(position, fragment);
notifyDataSetChanged();
}
#Override
public int getItemPosition(Object object) {
if (mFragmentList.contains(object)) return mFragmentList.indexOf(object);
else return POSITION_NONE;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment) {
mFragmentList.add(fragment);
notifyDataSetChanged();
}
}

SetOnItemClickListener error in TabbedActivity with fragments

So, I have a tabbed Activity called "Onglets". There I created 2 fragments ( OngletCours and OngletNotes).
In OngletCours I have a ListView, and I want to be able to swap to my 2nd fragment (OngletNotes), the name of the Item I clicked ( setonItemClickListener). But when I click on an Item, it doenst go to my 2nd fragment. It remains in the 1st fragment but the content of the 2nd Fragment appears in my current Fragment (OngletCours). I mean, I want to go the 2nd tab when I click on an Item of my listView in my 1st tab
Before clicking on an Item, my app looks like this :
Before clicking on an Item
After clicking on an Item you can see that the text "Onglet des résultats", is inserted at the top. But I dont want that. I want to go to the 2nd tab "Notes".
After clicking on an Item
Here's the code from my TabbedActivity
Onglets.java
public class Onglets extends AppCompatActivity {
DatabaseHelper dbhelper = new DatabaseHelper(this);
/**
* 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_onglets);
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);
}
#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_onglets, 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
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) {
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.ongletcours, 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.
*/
//méthode qui retourne une Fragment qui correspond à chacun des onglets
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
//switch qui retourne la position des différents Onglets
switch (position){
case 0:
OngletCours onglet1 = new OngletCours();
return onglet1;
case 1:
OngletNotes onglet2 = new OngletNotes();
return onglet2;
default:
return null;
}
}
//méthode qui retourne le nombre d'onglets disponibles
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
//méthode qui sert à définir un titre à chaque Onglet
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "COURS";
case 1:
return "NOTES";
}
return null;
}
}
}
Here's the code of the 2 fragments.
OngletCours.java ( I only show you the setOnItemClickListener, because it's where the problems appear)
ListView l1 = (ListView) rootView.findViewById(R.id.ListCours);
//ce Listener permet de détecter si on clique sur un élément de la liste
l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
OngletNotes targetFragment = OngletNotes.newInstance();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.fragment_holder, targetFragment)
.commit();
}
});
OngletNotes.java
public class OngletNotes extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.ongletnotes, container, false);
return rootView;
}
public static OngletNotes newInstance() {
OngletNotes fragment = new OngletNotes();
// put values which you want to pass to fragment
// Bundle args = new Bundle();
// fragment.setArguments(args);
return fragment;
}
}
Please help me to solve this and thank you in advance !
You can refer this method to trandfer the data from the one fragment to another
//Put the value
YourNewFragment ldf = new YourNewFragment ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);
//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();
In onCreateView of the new Fragment:
//Retrieve the value
String value = getArguments().getString("YourKey");
After clicking on an Item you can see that the text "Onglet des
résultats", is inserted at the top. But I dont want that. I want to go
to the 2nd tab "Notes"
You create 2 fragments at the same time, so, your fragment OngletNotes is initiazlied and you can pass data from fragment OngletCours to the second fragment. You create a method changeData(String data).
YOu code above create another fragment abvove current fragment, so the image 2 like you see
public class OngletNotes extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.ongletnotes, container, false);
return rootView;
}
public static OngletNotes newInstance() {
OngletNotes fragment = new OngletNotes();
// put values which you want to pass to fragment
// Bundle args = new Bundle();
// fragment.setArguments(args);
return fragment;
}
public void changeData(String data)
// DO something
}
Now, after you handle click listener from fragment OngletCours, you can pass data to fragment OngletNotes
l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
OngletNotes fragment = ((Onglets)getActviity())getOngletNotes ();
if(fragment != null) {
fragment.changeData("Set you value to send here");
}
((Onglets)getActviity()).goToFragment(1);
}
});
In you Onglets Activity
public OngletNotes getOngletNotes () {
return (OngletNotes ) getSupportFragmentManager().findFragmentByTag(
"android:switcher:" + R.id.viewPager + ":" + 1);
}
public void goToFragment (int index) {
mViewPager.setCurrentItem(index)
}

Using separated Intent for each fragmented tabs in Android

I'm trying to create tabs with swipe view using fragment. I found a solution but it provides a single dummy text layout for each tabs instead of using separated layout. I'd like to create three different classes with three different layouts and use them in tabs and if possible then using a custom background for each tabs (while selected/not selected). I can do all these things without fragment but using fragment it seems challenging.
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
To achieve your target you must use ActionBarSherlock library, and to call other fragments you should not need to use Intent,
I have written same kind of program few months ago to call different Fragments i used below code
#Override
public Fragment getItem(int arg0) {
switch (arg0) {
// Open FragmentTab1.java
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
// Open FragmentTab3.java
case 2:
FragmentTab3 fragmenttab3 = new FragmentTab3();
return fragmenttab3;
}
return null;
}
and to call show different - different layouts for each and every Fragment you should call different - different Fragments and also need to write XMLs too .....
FragmentTab1.java :-
public class FragmentTab1 extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.fragment1, container, false);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
}
fragment1.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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Your Layout Goes Here for Fragment1" />
</RelativeLayout>
in a same way you have to write classes and xmls for all needed Fragments....
for more detailed information or to try out an example, use this :
http://www.androidbegin.com/tutorial/android-actionbarsherlock-viewpager-tabs-tutorial/
in the following link that help you how to create Tab fragment in sperated intents:
Tab Fragments

Populate 5 fragment pages with separate arraylists

I've been stuck for days on this. I have an activity that will parse html and sort the information into 5 arraylists. Each arraylist is a weekday. I want to take each arraylist and display the information in a listview on a separate page, so monday will be displayed on one page and then by swiping you move to tuesday and so on.
I have taken the eclipse default scrollable tabs + swipe for navigation and I'm trying to build from there.
So essentially I want to populate 5 pages of data with 5 arraylists, 1 arraylist for each page. Any ideas how I assign an arraylist to listview in a specific page?
Here is the code I have so far
public class DisplayOnlineTimetable extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
String value;
Document doc = null;
private ListView mainListView ;
static ViewGroup mViewGroup;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_display_online_timetable_dummy);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_online_timetable, 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 i) {
return DummySectionFragment.newInstance(i);
}
#Override
public int getCount() {
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
//monday
case 0:
return getString(R.string.title_section1).toUpperCase(l);
//tuesday
case 1:
return getString(R.string.title_section2).toUpperCase(l);
//wednesday
case 2:
return getString(R.string.title_section3).toUpperCase(l);
//thursday
case 3:
return getString(R.string.title_section3).toUpperCase(l);
//friday
case 4:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public void createTimetable(ArrayList<SingleClass> list, Elements elements, Day day)
{
}
private class CreateTimetables extends AsyncTask<URL, Integer, Long>
{
protected Long doInBackground(URL... urls) {
}
protected void onPostExecute(Long result)
{
}
}
}
DummySectionFragment Class
public class DummySectionFragment extends ListFragment {
private Integer arrayListId;
ViewGroup myViewGroup;
public static final String CATEGORY_POSITION = "section_number";
public static DummySectionFragment newInstance(int pos) {
DummySectionFragment f = new DummySectionFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt(CATEGORY_POSITION, pos);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
//get the id for your array list
arrayListId = getArguments() != null ? getArguments().getInt(CATEGORY_POSITION) - 1 : 1;
}
//create the list view layout
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myViewGroup = container;
View v = inflater.inflate(R.layout.list_row, container, false);
return v;
}
//populate the list view row
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<SingleClass> arrayAdapter =
new ArrayAdapter<SingleClass>(getActivity(), android.R.id.list, R.layout.list_row);
setListAdapter(arrayAdapter);
}
}
What you need to do is standard, and you are almost there.
First in your ViewPager adapter's getItem methods, initiate the Fragment with which position it is on:
#Override
public Fragment getItem(int i) {
return DummySectionFragment.newInstance(i);
}
Next, in your Fragment class, create a constructor to instantiate it:
public static DummySectionFragment newInstance(int pos) {
DummySectionFragment f = new DummySectionFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt(CATEGORY_POSITION, pos);
f.setArguments(args);
return f;
}
And now make your DummySectionFragment extend a ListFragment, and in the onActivityCreated method you can populate it:
public class DummySectionFragment extends ListFragment {
private Integer arrayListId;
//the constructor from above
#Override
public void onCreate(Bundle savedInstanceState) {
//get the id for your array list
arrayListId = getArguments() != null ? getArguments().getInt(CATEGORY_POSITION) - 1 : 1;
}
//create the list view layout
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myViewGroup = container;
View v = inflater.inflate(R.layout.fragment_list, container, false);
return v;
}
//populate the list view row
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this, android.R.layout.list, <your_array_list_row.xml>);
setListAdapter(adapter);
}
}
The above code for your Fragment class will get the id for your array based on the position of the fragment, and create an ArrayAdapter for it, and use this adapter to populate a listview fragment. Now all you have to do is create the xml layout for the list:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
One last thing is make sure all your Fragment class are from the same set of library (eg. either the regular Fragment lib or support.v4).

How to put more views in a page title strip?

I'm trying to use a page title strip and I need to put three seekbars in one of my fragments. This is my code:
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);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = null;
Bundle args = new Bundle();
switch (position) {
case 0:
fragment = new Page1();
args.putInt(Page1.ARG_SECTION_NUMBER, position + 1);
break;
case 1:
fragment = new Page2();
args.putInt(Page2.ARG_SECTION_NUMBER, position + 1);
break;
case 2:
fragment = new Page3();
args.putInt(Page3.ARG_SECTION_NUMBER, position + 1);
break;
}
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
case 2:
return getString(R.string.title_section3).toUpperCase();
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class Page1 extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public Page1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create a new TextView and set its text to the fragment's section
// number argument value.
// TextView textView = new TextView(getActivity());
// textView.setGravity(Gravity.CENTER);
// textView.setText(Integer.toString(getArguments().getInt(
// ARG_SECTION_NUMBER)));
SeekBar sb1 = new SeekBar(getActivity());
SeekBar sb2 = new SeekBar(getActivity());
SeekBar sb3 = new SeekBar(getActivity());
return sb1;
}
}
public static class Page2 extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public Page2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create a new TextView and set its text to the fragment's section
// number argument value.
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.LEFT);
textView.setText("Second tab");
return textView;
}
}
public static class Page3 extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public Page3() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create a new TextView and set its text to the fragment's section
// number argument value.
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.RIGHT);
textView.setText("third tab");
return textView;
}
}
}
This actually works but I only have one seekbar in the first page. Ho can I put the three of them??? Thanks!!!!
on this code:
SeekBar sb1 = new SeekBar(getActivity());
SeekBar sb2 = new SeekBar(getActivity());
SeekBar sb3 = new SeekBar(getActivity());
return sb1;
you're creating 3 SeekBars but only returning the first one. The other two are being garbage collected quickly after that return statement.
Inside the onCreateView method you must create a GroupView, and this group will have the 3 SeekBars or whatever layout you need. The best/easiest way to do it is creating a XML layout and use the LayoutInflater that is passed on the function. Something similar to:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_page1, null);
}

Categories

Resources