I know there are a lot of similar questions here, but none of them have worked for me so far, so I'm hoping by just posting my (slightly redacted) class here, someone can help me out. It's a ViewPager using 4 fragments as the pages.
So my problem is that the method getFragmentByPosition isn't working, because getSupportFragmentManager() is returning null. Up in my onCreate, mSectionsPagerAdapter is also returning null if I try to call anything from that, however my tabs all show up fine, and I'm just not able to access the data from my fragments that I need.
I really don't know what the issue is at this point, so any help is appreciated. I posted a few other questions before, and tried the suggestions to no avail, so now I'm just posting up my entire class. Thanks!
package com.me.testapp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import com.me.testapp.CheckListFragments.Thing1Fragment;
import com.me.testapp.CheckListFragments.Thing2Fragment;
import com.me.testapp.CheckListFragments.Thing3Fragment;
import com.me.testapp.CheckListFragments.Thing4Fragment;
import com.me.testapp.Data.ClientDAO;
import io.karim.MaterialTabs;
public class CheckList extends AppCompatActivity
implements Thing1Fragment.OnFragmentInteractionListener,
Thing2Fragment.OnFragmentInteractionListener,
Thing3Fragment.OnFragmentInteractionListener,
Thing4Fragment.OnFragmentInteractionListener {
/**
* 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}.
*/
/**
* The {#link ViewPager} that will host the section contents.
*/
public SectionsPagerAdapter mSectionsPagerAdapter;
public ViewPager pager;
private ClientDAO clientDAO;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklist);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView toolbarName = (TextView) findViewById(R.id.toolbar_name);
TextView toolbarFloor = (TextView) findViewById(R.id.toolbar_floor);
TextView toolbarOffice = (TextView) findViewById(R.id.toolbar_office);
toolbarName.setText(getIntent().getStringExtra("Name"));
toolbarRoom.setText(": " + getIntent().getStringExtra("Office"));
toolbarFloor.setVisibility(View.GONE);
// Initialize the ViewPager and set an adapter
pager = (ViewPager) findViewById(R.id.pager);
mSectionsPagerAdapter = new SectionsPagerAdapter(this.getSupportFragmentManager());
pager.setAdapter(mSectionsPagerAdapter);
pager.setOffscreenPageLimit(3);
// Bind the tabs to the ViewPager
MaterialTabs tabs = (MaterialTabs) findViewById(R.id.tabs);
tabs.setViewPager(pager);
clientDAO = new ClientDAO(getApplicationContext());
}
#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_checklist, 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 {#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).
switch(position) {
case 0:
Thing1Fragment thing1 = new Thing1Fragment();
return thing1;
case 1:
Thing2Fragment thing2 = new Thing2Fragment();
return thing2;
case 2:
Thing3Fragment thing3 = new Thing3Fragment();
return thing3;
case 3:
Thing4Fragment thing4 = new Thing4Fragment();
return thing4;
default:
thing1 = new Thing1Fragment();
return thing1;
}
}
#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;
}
}
public void onFragmentInteraction(Uri uri){
//you can leave it empty
}
public int booleanToInt(boolean bool) {
return bool ? 1 : 0;
}
public Fragment getFragmentByPosition(int pos) {
String tag = "android:switcher:" + R.id.pager + ":" + pos;
return getSupportFragmentManager().findFragmentByTag(tag);
}
public int getCheckboxState(int id, String page) {
switch (page) {
case "thing1":
return booleanToInt(((CheckBox) getFragmentByPosition(0).getView().findViewById(id)).isChecked());
case "thing2":
return booleanToInt(((CheckBox) getFragmentByPosition(1).getView().findViewById(id)).isChecked());
case "thing3":
return booleanToInt(((CheckBox) getFragmentByPosition(2).getView().findViewById(id)).isChecked());
case "thing4":
return booleanToInt(((CheckBox) getFragmentByPosition(3).getView().findViewById(id)).isChecked());
default:
return booleanToInt(((CheckBox) getFragmentByPosition(0).getView().findViewById(id)).isChecked());
}
}
}
I was having the same problem.
What I deduce it about the lifecycle of the activity, in the method onCreate the activity isn't totally created so when you try to pass getSupportFragmentManager its null.
What I do to resolve it, is putting this lines of code in onStart. The problem there is that each time the activity is paused and run it again the Fragment will be restarting.
Related
I'm making a tabbed application and need a way to do an action on when I change a tab. The problem is that all I can find is about TabHost which relies on the deprecated TabActivity class. Even if it wasn't deprecated the pre-generated tabbed activity code doesn't even use it, so I'd have to build my main activity class from the ground up. So I want to know if there is another way to get that functionality
rough skeleton of the code
public class MainActivity extends AppCompatActivity implements TabHost.OnTabChangeListener{
public class SectionsPagerAdapter extends FragmentPagerAdapter {
}
}
Let's pretend that you are using Android Studio 1.5.1.
When I create a project using the new-project wizard, and accept the defaults, except choosing "Tabbed Activity" as the template, on the activity-configuration page of the wizard, there is a drop-down for "Navigation Style". There are three options there: "Swipe Views", "Action Bar Tabs", and "Action Bar Spinner".
Let's pretend that you chose "Action Bar Tabs".
The resulting activity does not have implements TabHost.OnTabChangeListener, and I am not aware of any of their templates that do. Instead, you get this:
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will
* provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep
* every
* loaded fragment in memory. If this becomes too memory
* intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter=
new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager=(ViewPager)findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout=(TabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
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();
}
});
}
#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, 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) {
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_main, 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;
}
#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;
}
}
}
If this is where you started, the proper response to "explain exactly what you are using right now" would have been "AppCompatActivity, ViewPager, and TabLayout".
Let's pretend that this is what you have, more or less.
In that case, call addOnPageChangeListener() on the ViewPager, passing in an OnPageChangeListener implementation. That will be called when the user switches tabs, whether via the TabLayout or by swipe gestures on the ViewPager itself.
Now, it is entirely possible that this is not what you have, as I had to make a few guesses, given your limited explanation in your question.
I have just started working with android studio and developing with tabbed fragments. I am trying to build a simple app with three fragments, each fragment is going to have its own required input. I know this requires working with the content of each fragment, I am not sure how to do that. I want the first fragment to have one button, the second one two, the third one, three. And I want to design each of these as an activity and have them started by tabbing/swiping thru. Rightnow this is my code:
package com.example.riskcalculator;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
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();
}
});
}
#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, 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) {
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_main, 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;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SYSTEM A";
case 1:
return "SYSTEM B";
case 2:
return "SYSTEM C";
}
return null;
}
}
}
If you have three different classes for each fragments, then you can add, button in the fragment layout as per your requirements.
If you are using just one fragment instance class.
Then, one approach would be to tag the fragment, with some id and get it by tag id and create button from program.
or
If you have just 3 or 4 tabs, then you can just check it in the getItem() callback, by checking position and pass a variable or something to the fragment, and based on passed value you can create buttons as per your need.
It may be dumb question but it is still confusing how to pass navigate data from activity to fragment of other activity how can i achieve this i have searched and tired still i cannot find anything can somebody help me out. Now let me tell my requirement am having tabactivity in one of the tab i have listview when i click listivew item it must goes to other activity where the data will go and populate the listview in tabs how can i achieve this so far what i have tried is
This is my tab activity:
package servicefiirst.precision.activitiestabs;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
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();
}
});
}
#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, 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.
*/
/**
* 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).
switch (position){
case 0:
Task task=new Task();
return task;
case 1:
Calls calls=new Calls();
return calls;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Task";
case 1:
return "Call";
}
return null;
}
}
}
This is the fragment where listview getspopulated:
package servicefiirst.precision.activitiestabs;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by 4264 on 08-01-2016.
*/
public class Task extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview= inflater.inflate(R.layout.yog,container,false);
Listview lv=(Listview)rootview.findviewbyId(R.id.lv);
lv.setOnItemClickListener(new OnItemClickListener(
#Override
public void onClick(View v) {
Intent intent=new Intent(getActivity,DetailActivity.class)
startactivity(intent);
}
});
return rootview;
}
}
Use a bundle to transfer data from one activity to another activity
Bundle bundle = new Bundle();
bundle.putString("KEY_NAME", "Abrakadabra");
Intent i = new Intent(this, MyActivityName.class);
i.putExtras(bundle);
startActivity(i) <-- new activity started
Then in the receiving activity: Put this code in the onCreate method
Bundle bundle = getIntent().getExtras();
String stringdata = bundle.getString("KEY_NAME");
To pass data from activity to fragment: Put this code anywhere
Bundle bundle = new Bundle();
bundle.putString("KEY_NAME", "Abrakadabra");
MyFragment myfragment = new MyFragment();
myfragment.setArguments(bundle);
Then in the onCreateView method of the fragment add this code
Bundle args = getArguments();
String stringdata = args.getString("KEY_NAME");
Try this for sending data to another activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView c = (TextView) view.findViewById(R.id.label);
String source = c.getText().toString();
Intent intent = new Intent(MetroFrom.this, Metro.class);
intent.putExtra("From", source);
startActivity(intent);
}
});
Then put this code on which activity you want to receive data
Intent intent = getIntent();
etsource.setText(intent.getStringExtra("from"));
So it seems the previous ways of creating tabbed activities that allow swiping the screen left and right have all been deprecated.
I tried searching through various other guides, but all of them use deprecated fragments methods.
So I tried using the built in "Tabbed Activity" in Eclipse here:
New -> Other -> Android Activity -> Tabbed Activity
I created 2 additional fragment activities called fragment2_activity, fragment3_activity.
Going by that, where in the code below do I add the second and third fragments?
import java.util.Locale;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v13.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class InformationActivity extends Activity {
/**
* 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.v13.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_information);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// 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.information, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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) {
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 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";
/**
* 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_information,
container, false);
return rootView;
}
}
}
I managed to fix my problem, I was importing an incorrect package.
I'm learning to create application on android and I have a problem with the fragment functionality.
I created a new black activity using eclipse and selecting the "Swipe views+title strip" navigation type.
I ran it and it's fully working displaying Section 1, Section 2, Section 3.
What I wanted to do is selecting a different layout for each section so i tweaked the code this way :
package fr.mpsn.networkclient;
import android.R.layout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class HomeActivity 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_home);
// 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_home, 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.
Log.i("info", ""+position);
Fragment fragment = new DummySectionFragment("view_publishmessage");
switch (position) {
case 0:
fragment =null;
fragment = new DummySectionFragment("view_publishmessage");
case 1:
fragment =null;
fragment = new DummySectionFragment("view_timeline");
case 2:
fragment =null;
fragment = new DummySectionFragment("view_profile");
}
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) {
switch (position) {
case 0:
return "Nouvelle publication".toUpperCase();
case 1:
return "Timeline".toUpperCase();
case 2:
return "Profil".toUpperCase();
}
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 final String fragmentLayoutName;
public DummySectionFragment(String fragmentLayoutName) {
this.fragmentLayoutName = fragmentLayoutName;
}
#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.
return inflater.inflate(
this.getResources().getIdentifier(this.fragmentLayoutName,
"layout", "fr.mpsn.networkclient"), null);
}
}
}
The problem is that all the different section uses the view profile layout even if the case is correctly parsed...
Have you got any idea on how can I improve this code to make it work better?
Didn't you miss some break statement in your switch?
without it, the code continue to the next case:
switch(cond) {
case A:
print("hello!");
//break;
case B:
print("hello again!");
//break;
}
=>
hello!
hello again!
Also, it is better to use empty constructor for fragment, otherwise you'll have problem when the fragment is re-created (after a configuration change for example).
See Do fragments really need an empty constructor?
You can use Fragment.setArguments() and Fragment.getArguments() to pass your fragmentLayoutName.