Adding ViewPager into Existing TabHost - android

Hi I would like to add view pager into existing code. What is the best way to add. Here is my RssTabActivitty.java and RssChannelActivity.java.
RssTabActivity is my main activity to initialize the tabs.
RssChannelActivity is load the rss feed.
here is full source code
https://github.com/itcuties/Android-Multicategory-RSS-Reader
public class RssTabsActivity extends TabActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// First, set the content view
setContentView(R.layout.activity_rss_tabs);
// Then get the TabHost
TabHost tabHost = getTabHost();
/* *****************
* Art tab
*/
Intent artIntent = new Intent().setClass(this, RssChannelActivity.class);
// Set Art category RSS URL
artIntent.putExtra("rss-url", "http://feeds.reuters.com/news/artsculture?format=xml");
// The name of the art tab taken from the String resources
String artTabName = getResources().getString(R.string.tab_art);
TabSpec artTabSpec = tabHost.newTabSpec(artTabName)
.setIndicator(artTabName, getResources().getDrawable(R.drawable.rss_tab_art))
.setContent(artIntent);
// Add art tab to the TabHost
tabHost.addTab(artTabSpec);
/* *****************
* Tech tab
*/
Intent techIntent = new Intent().setClass(this, RssChannelActivity.class);
// Set Tech category RSS URL
techIntent.putExtra("rss-url", "http://feeds.reuters.com/reuters/technologyNews?format=xml");
// Tech tab name taken from the string resources
String techTabName = getResources().getString(R.string.tab_tech);
TabSpec techTabSpec = tabHost.newTabSpec(techTabName)
.setIndicator(techTabName, getResources().getDrawable(R.drawable.rss_tab_tech))
.setContent(techIntent);
// Add tech tab to the TabHost
tabHost.addTab(techTabSpec);
/* *****************
* Sports tab
*/
Intent sportsIntent = new Intent().setClass(this, RssChannelActivity.class);
// Set Sports category RSS URL
sportsIntent.putExtra("rss-url", "http://feeds.reuters.com/reuters/sportsNews?format=xml");
// Sports tab name - string resources
String sportsTabName = getResources().getString(R.string.tab_sports);
TabSpec sportsTabSpec = tabHost.newTabSpec(sportsTabName)
.setIndicator(sportsTabName, getResources().getDrawable(R.drawable.rss_tab_sports))
.setContent(sportsIntent);
// Add sports tab to the TabHost
tabHost.addTab(sportsTabSpec);
// Set current tab to Technology
tabHost.setCurrentTab(1);
}
}
public class RssChannelActivity extends Activity {
// A reference to this activity
private RssChannelActivity local;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rss_channel);
// Get the RSS URL that was set in the RssTabActivity
String rssUrl = (String)getIntent().getExtras().get("rss-url");
// Set reference to this activity
local = this;
GetRSSDataTask task = new GetRSSDataTask();
// Start process RSS task
task.execute(rssUrl);
}
/**
* This class downloads and parses RSS Channel feed.
*
* #author itcuties
*
*/
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
try {
// Create RSS reader
RssReader rssReader = new RssReader(urls[0]);
// Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("RssChannelActivity", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
// Get a ListView from the RSS Channel view
ListView itcItems = (ListView) findViewById(R.id.rssChannelListView);
// Create a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1, result);
// Set list adapter for the ListView
itcItems.setAdapter(adapter);
// Set list view item click listener
itcItems.setOnItemClickListener(new ListListener(result, local));
}
}
}

To add a view pager to your activity:
Add the ViewPager resource to your activity resource:
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
Create the fragment resource of your pager:
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Create the fragment class of your fragment:
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;
}
}
Create the adapter class of your pager:
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;
}
}
Use the pager in your activity (Your activity must extend FragmentActivity):
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);

Related

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)
}

Better way to populate/manage views in 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.

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);
}

ListView in Fragment is not shown when using ActionBar with Tabs in Android 4

I created an activity with ActionBar and tabs using the Eclipse wizard. I want to show ListViews inside my three tabs but if they are not shown when I run my app.
The code for the activity with the Tabs:
public class CreateProjectManually 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
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_project_manually);
// 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 action bar.
final ActionBar actionBar = getActionBar();
// set the app icon as an action to go home
actionBar.setDisplayHomeAsUpEnabled(true);
//enable tabs in actionbar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// 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
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
/**
* Actionbar
* */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
//TODO Speichern implementieren
Toast.makeText(getBaseContext(), "Speichern",Toast.LENGTH_LONG).show();
break;
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, ProjectList.class);
intent.putExtra("Uniqid","From_CreateProjectManually_Activity");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
return true;
default:
break;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_create_project_manually, menu);
return true;
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#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 onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return getString(R.string.building).toUpperCase();
case 1: return getString(R.string.room).toUpperCase();
case 2: return getString(R.string.devices).toUpperCase();
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public DummySectionFragment() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return (LinearLayout) inflater.inflate(R.layout.listviews, container, false);
}
}
}
And the XML-file for the layout with the ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="259dp" >
</ListView>
</LinearLayout>
</LinearLayout>
The TextView is shown but the ListView not. What is the problem?
First you have to create your adapter for the list view that yo have with it's own custom row and find it's id in the onCreateView method based on on the root view like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_calendar_dummy,
container, false);
/*TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)) + "HOLA");*/
//getFavorito(ARG_SECTION_NUMBER);
//asyncFavorite().execute(ARG_SECTION_NUMBER);
lista = (ListView) rootView.findViewById(R.id.Your own list);
loadingLista = (RelativeLayout) rootView.findViewById(R.id.loadingLista);
int mes = getArguments().getInt(ARG_SECTION_NUMBER);
new asyncFavorite().execute(Integer.toString(mes));
Log.i("mfb", "puse el-----------------" + Integer.toString(mes));
return rootView;
}
after this you have to create a method to inflate your list, create an array list of your object that contains all the elements of the list and use it to inflate all the rows:
m_orders = new ArrayList<Order>();
//JSONObject data = new JSONObject(Fetcher.getMonthBirthday(FBAccount, params[0]));
//resData = data.getJSONArray("data");
//Log.i("mfb", "RESDATA::::::::::" + resData + "////////////////////" +Index.userID);
JSONObject objeto = null;
String nombre = "";
String cumpliendo = "";
String mes = "";
String dia = "";
String uuid = "";
String favorite = "";
String ownerID = "";
int mesNumero = 0;
String[] cumple = null;
String pasoMes = "";
for(int i = 0; i<resData.length(); i++){
objeto = resData.getJSONObject(i);
nombre = objeto.getString("name");
cumpliendo = objeto.getString("edad");
cumple = objeto.getString("birthday").split("-");
dia = cumple[2];
pasoMes = cumple[1];
mesNumero = Integer.parseInt(pasoMes);
//mes = getMes(mesNumero);
uuid = objeto.getString("uuid");
favorite = "1";
ownerID = objeto.getString("user_id");
m_orders.add(i, new Order(""+nombre, ""+cumpliendo, ""+mes, ""+dia, "" + uuid, ""+favorite, ""+ownerID, "" + FBAccount));
//Log.i("mfb", "HH " + nombre);
}
the you have to set the adapter to your list
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Log.v("mfb", " Runnable "+m_orders.size());
adapterOrder = new orderItemAdapter(activity.getApplicationContext(), android.R.layout.simple_list_item_1, m_orders);
lista.setAdapter(adapterOrder);
adapterOrder.notifyDataSetChanged();
}catch (NullPointerException e){
Log.e("Error", " generateAdapter NullPointerException ERROR => "+e.getMessage());
}catch (Exception e) {
// TODO: handle exception
Log.e("Error", " generateAdapter Exception ERROR => "+e.getMessage());
}
}
});
the adapter is something like this:
public class orderItemAdapter extends ArrayAdapter<Order>{
public ArrayList<Order> orders;
LayoutInflater inflater = null;
public orderItemAdapter(Context context, int textViewResourceId, ArrayList<Order> orders){
super(context, textViewResourceId, orders);
this.orders = orders;
Log.v("mfb", "orderItem "+this.orders.size());
}
public void add(int index, Order order){
this.orders.add(index, order);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View vi=convertView;
LayoutInflater inflater = null;
if(convertView==null){
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_user, null);
}
Order order = orders.get(position);
if(order != null){
TextView nombre = (TextView)vi.findViewById(R.id.nombre);
TextView edadCumplir = (TextView)vi.findViewById(R.id.edadCumplir);
//TextView mes = (TextView)vi.findViewById(R.id.mes);
TextView dia = (TextView)vi.findViewById(R.id.dia);
//Log.v("mfb", " order position => "+position);
if(nombre != null){
nombre.setText(orders.get(position).getNombre());
//Log.v("mfb", "orderItemAdapter nombre =>" + nombre.getText());
}
if(edadCumplir != null){
edadCumplir.setText("Turning " + orders.get(position).getCumpliendo());
}
/*if(mes != null){
mes.setText(orders.get(position).getMes());
}*/
if(dia != null){
dia.setText(orders.get(position).getDia());
}
}
return vi;
}
}

Categories

Resources