I am new to Android programming.
I have the following layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/fundo"
android:background="#color/roxo"
tools:context="com.fnsp.anedotaspiadas.Anedotas" />
<LinearLayout
android:id="#+id/fundo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/adView"
android:layout_alignParentBottom="true"
android:background="#color/roxo"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/previousButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/previous" />
<ImageButton
android:id="#+id/voltarButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/voltar" />
<TextView
android:id="#+id/counter"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="TextView" />
<ImageButton
android:id="#+id/nextButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/next" />
</LinearLayout>
</RelativeLayout>
Fragment Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.fnsp.anedotaspiadas.Anedotas$PlaceholderFragment" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true" >
<TextView
android:id="#+id/section_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:padding="#dimen/padding"
android:textColor="#color/branco"
android:textSize="20sp" />
</ScrollView>
</RelativeLayout>
The buttons are outside the fragment, but I want the buttons be able to switch between fragment, and the textView show the fragment number. I started with the textView, but when i try to print the number, it doesn't print the right number, and when i swipe he sometimes he jumps several numbers.
public class Anedotas extends ActionBarActivity {
DBTools dbTools = new DBTools(this);
static ArrayList<String> ar = new ArrayList<String>();
private static TextView counter;
private ImageButton previous;
private ImageButton next;
private ImageButton voltar;
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_anedotas);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
int aux = Integer.parseInt(extras.getString("categoria"));
this.setTitle(dbTools.retornaNomeCategoria(aux));
counter = (TextView) findViewById(R.id.counter);
previous = (ImageButton) findViewById(R.id.previousButton);
next = (ImageButton) findViewById(R.id.nextButton);
previous = (ImageButton) findViewById(R.id.voltarButton);
//buscar as anedotas...
ar = dbTools.getAnedotasCategoria(aux);
// 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.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//alteraBarraInferior();
}
#Override
public void onResume(){
super.onResume();
}
#Override
public void onPause(){
super.onPause();
//this.finish();
}
/**
* 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 ar.size();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private final static 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_anedotas, container, false);
Bundle args = getArguments();
int i = args.getInt(ARG_SECTION_NUMBER);
String help = i+"/"+ar.size();
counter.setText(help);
((TextView) rootView.findViewById(R.id.section_label)).setText(Html.fromHtml(ar.get(i-1)));
return rootView;
}
}
}
Does anyone know what the problem is? and even now, how can I create a ClickListener to call the previous or the next fragment.
I thank you for your help and availability.
To be able to print current ViewPager position you should use OnPageChangeListener of ViewPager:
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
counter.setText(String.valueOf(position));
}
});
To change current position (fragment switching) of ViewPager you should use ViewPager.setCurrentItem method:
pager.setCurrentItem(1)
1 here is position of your fragment. This should be invoked from onClick listeners of your buttons. Of course, you should change that 1 to correct value.
Why is it incorrect to print current position from onCreateView?
ViewPager initialize several fragments at once due to its implementation. For instance, you have 5 fragments in your ViewPager and ViewPager is about to show Fragment #3. It will initialize Fragment #3, Fragment #2 and Fragment #4. So onCreateView of these 3 fragments will be invoked, and that's why you'll get wrong position.
Related
I am trying to change the fragment when I click on a button. The button is inside a fragment and I want to go to another fragment. This code is not giving any error but not changing to desired fragment. It is just showing the background of container. Please help me why it is just showing the color of container and not changing to new fragment.
Here is my first Fragment-
public class IntroFragment1 extends Fragment {
public IntroFragment1() {
// Required empty public constructor
}
public static IntroFragment1 newInstance() {
return new IntroFragment1();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_intro1, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
/**
* Button to go to next tab in tutorial
* */
Button nextScreen = getView().findViewById(R.id.nextTabButtonIntro);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (vb1 != null) {
vb1.vibrate(300);
}
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment frag = IntroFragment2.newInstance();
transaction.replace(R.id.containerIntroScreen, frag);
transaction.commit();
}
});
}//End of onViewCreated
}
This is the XML of first Fragment. The next Button should take me to next fragment-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
android:orientation="vertical"
android:weightSum="1"
tools:context="com.example.fitbitsampleapp.AppIntroTabbedView.IntroFragment1">
<TextView
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="casual"
android:text="Track your daily activities. Stay healthy, Stay smart."
android:textSize="26dp" />
<Button
android:id="#+id/skipIntoButton"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_weight="1"
android:background="#drawable/background_button"
android:fontFamily="casual"
android:text="skip"
android:textAllCaps="true"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Large"
android:textColor="#000" />
<Button
android:id="#+id/nextTabButtonIntro"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_weight="1"
android:background="#drawable/background_button"
android:fontFamily="casual"
android:text="next"
android:textAllCaps="true"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Large"
android:textColor="#000" />
</LinearLayout>
This is the fragment, I want to go to-
public class IntroFragment2 extends Fragment {
public IntroFragment2() {
// Required empty public constructor
}
public static android.support.v4.app.Fragment newInstance() {
IntroFragment2 fragment = new IntroFragment2();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_intro2, container, false);
}
The XML of the 2nd Fragment-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context="com.example.fitbitsampleapp.AppIntroTabbedView.IntroFragment2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:text="2nd fragment" />
</RelativeLayout>
This is the layout of activity which has the fragments-
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.fitbitsampleapp.AppIntroTabbedView.IntroScreen">
<android.support.v4.view.ViewPager
android:background="#00F111"
android:id="#+id/containerIntroScreen"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
So initially the app opens with 1st transaction as expected. However when I click on next button in fragment 1, it should take me to fragment 2. But it just shows the Background color of ViewPager after the Fragment Transaction.
EDIT:
Here is my Main Activity as well which has the fragments-
public class IntroScreen extends AppCompatActivity {
public static Vibrator vb1;
public Button nextScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro_screen);
/***/
vb1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
/**
* Create the adapter that will return a fragment
* for each of the N primary sections of the activity.
* */
SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
/** Set up the ViewPager with the sections adapter.*/
ViewPager mViewPager = findViewById(R.id.containerIntroScreen);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
switch (position) {
case 0:
return IntroFragment1.newInstance();
case 1:
return IntroFragment2.newInstance();
default:
return IntroFragment2.newInstance();
}
}
#Override
public int getCount() {
return 2;
}
}
}
SOLVED BY #MikeM. in the comments above.
Since I was already using a ViewPager, All that was required was to give the correct item number to my ViewPager.
int THE_POSITION_OF_THE_FRAGMENT_IN_VIEW_PAGER = 1;
mViewPager.setCurrentItem(THE_POSITION_OF_THE_FRAGMENT_IN_VIEW_PAGER);
I am sorry on the duplicate question but I didn't get answer for my problem.
I create app with TabActivity and also trying to replace one fragment from fragment itself, I read in https://developer.android.com/training/basics/fragments/fragment-ui.html how to do it and i created interface in my fragment that i want to be replace with another,
I implement the interface in my MainActivity and still when running my app it show me container itself.
here is my code:
Main Activity:
public class MainActivity extends FragmentActivity implements New2.OnReplaceFragment {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static MainActivity instance = null;
public static MainActivity getInstance(){
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
instance = this;
}
#Override
public void onReplaceFragment(Class fragmentClass) {
Fragment fragment = null;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container,fragment);
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
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() {
}
#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;
}
}
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:
// New1 tab1 = new New1();
return New1.newInstance();
case 1:
return New2.newInstance();
case 2:
return New3.newInstance();
default:
return null;
}
}
#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;
}
}
}
my fragment that I want to replace
Fragment:
public class New2 extends Fragment {
TextView name;
Button change;
ImageView image1;
Animation anime;
private OnReplaceFragment dataPasser;
public static New2 newInstance(){
New2 fragment = new New2();
return fragment;
}
public New2(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new2, container, false);
name = (TextView) rootView.findViewById(R.id.nameTt);
change = (Button) rootView.findViewById(R.id.changeBtn);
image1 = (ImageView) rootView.findViewById(R.id.image1);
anime = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),R.anim.zoom);
change.setOnClickListener(changeName);
return rootView;
}
View.OnClickListener changeName = new View.OnClickListener() {
#Override
public void onClick(View view) {
image1.startAnimation(anime);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run(){
dataPasser.onReplaceFragment(Result.class);
}
},1000);
}
};
public interface OnReplaceFragment {
public void onReplaceFragment(Class fragmentClass);
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
try {
dataPasser = (OnReplaceFragment) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString() + " must implement onDataPass");
}
}
}
the fragment that i want to display
public class Result extends Fragment {
TextView textView;
Button btnBack;
public static Result instance = null;
public static Result getInstance(){
return instance;
}
public Result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_result, container, false);
textView = (TextView) v.findViewById(R.id.text11);
btnBack = (Button) v.findViewById(R.id.btnBack);
textView.setText("working!!");
Toast.makeText(getActivity().getApplicationContext(),"working",Toast.LENGTH_LONG).show();
return v;
}
}
Main Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.hercules.tadhosttutrial.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:background="#color/red"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
New2 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"
tools:context="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/changeBtn"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:text="change"/>
<ImageView
android:id="#+id/image1"
android:background="#drawable/icon_complete"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
Result XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context="com.example.hercules.tadhosttutrial.Result">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back"/>
<TextView
android:id="#+id/text11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WORKING"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="70dp"
/>
</RelativeLayout>
What i mean, is making MainActivity as a main container for all fragments, either with tabs or just a regular fragment,
1- Main Activity XML: remove ViewPager, add a FrameLayout instead (use same id)
2- Create new fragment TabsFragment with this 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"
tools:context="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
3- Move initializing SectionsPagerAdapter and ViewPager from main activity to TabsFragment:
this part:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
and this:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
4- I think moving SectionsPagerAdapter class in a new file is better too.
now if you want default view for app to be the tabs, then in MainActivity at onCreate() show TabsFragment by calling your method:
onReplaceFragment(TabsFragment.class);
now every thing should work fine, because the idea here is to replace the fragment displayed in main activity with another one
in this case TabsFragment, Result, and New2
not to replace viewpager fragments (because as i told you this is managed via the adapter) not by calling replace()
you may need to play around this, it's not a final code, just something to give you idea about it.
I am making use of PagerTabStrip in my android app like the ones used in the new Google play store app. I went through a few tutorials and was succesfull in creating three tabs. They are Information, Electronic Configuration and Facts
Information
Electronic Configuration
Facts
Here is the xml layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:textSize="30dp"
android:background="#000000"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#ffffff" />
</android.support.v4.view.ViewPager>
Here is the Java file
public class Tabs extends FragmentActivity
{
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.act2aluminium);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
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()
{
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0:
return "Information";
case 1:
return "Electronic Configuration";
case 2:
return "Facts";
}
return null;
}
}
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return textView;
}
}
}
Now, my question is How do I attach layouts or pages to the tabs instead of the tiny 1, 2, 3 textViews?
I've searched a lot but coudn't find a good explanation of how it's done. Please help me out with the code. Thanks in advance!
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:textSize="30dp"
android:background="#000000"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#ffffff" />
</android.support.v4.view.ViewPager>
page1.xml
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Click here" />
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/button1"
android:text="I am Page one" />
page2.xml
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Click here" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/button2"
android:text="I am Page two" />
page3.xml
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Click here" />
<TextView
android:id="#+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/button3"
android:text="I am Page three" />
MainActivity.java
public class MainActivity extends FragmentActivity
{
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position) {
case 0:
// Top Rated fragment activity
return new Information();
case 1:
// Games fragment activity
return new ElectonicConfiguration();
case 2:
// Movies fragment activity
return new Fact();
}
return null;
}
#Override
public int getCount()
{
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0:
return "Information";
case 1:
return "Electronic Configuration";
case 2:
return "Facts";
}
return null;
}
}
//Page 1 Fragment
public static class Information extends Fragment {
public Information()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.page1, null);
TextView textView = (TextView)view.findViewById(R.id.text1);
Button button=(Button)view.findViewById(R.id.button1);
return view ;
}
}
//Page 2 Fragment
public static class ElectonicConfiguration extends Fragment {
public ElectonicConfiguration()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.page2, null);
TextView textView = (TextView)view.findViewById(R.id.text2);
Button button=(Button)view.findViewById(R.id.button2);
return view ;
}
}
//Page 3 Fragment
public static class Fact extends Fragment {
public Fact()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.page3, null);
TextView textView = (TextView)view.findViewById(R.id.text3);
Button button=(Button)view.findViewById(R.id.button3);
return view ;
}
}
}
page1.xml, page2.xml,page3.xml are the layout file for the first,second and third page respectively.And There are 3 different fragments declared in the MainActivity.java for the 3 different pages. getItem() of SectionsPagerAdapter class manages all the 3 fragment pages. Make changes in the xml file as per your wish.I think the code is pretty self explanatory.If you have any doubt don't hesitate to ask.
Hope it helps. Cheers!
Halo guys, I followed the android developer steps:http://developer.android.com/training/animation/screen-slide.html
How can I call get the "btnRight" & "btnLeft" in MainJava to create a onClick function?
i have no idea about that, (???).findViewByID ?
btw, is there an another better coding design to create this effect?
i wanna create 3 page that can slide or maybe click to change screen, did i use this viewpager incorrectly? Is it probably add some new view instants of using the pagenumber trick?
please help me a bit, thanks!!
MainJava.java:
public class MainJava extends FragmentActivity {
private static final int NUM_PAGES = 3;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.hide();
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setCurrentItem(1);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
ScreenSlidePageFragment.java:
public class ScreenSlidePageFragment extends Fragment {
public static final String ARG_PAGE = "page";
private int mPageNumber;
public static ScreenSlidePageFragment create(int pageNumber) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public ScreenSlidePageFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
ViewGroup rootView = (ViewGroup) inflater
.inflate(R.layout.scroll_view_content, container, false);
//rootView.addView(inflater.inflate(R.layout.scroll_view_content, null));
View pageLeft = (View) rootView.findViewById(R.id.pageLeft);
View pageRight = (View) rootView.findViewById(R.id.pageRight);
View pageMain = (View) rootView.findViewById(R.id.pageMain);
if (mPageNumber==0){
pageLeft.setVisibility(View.VISIBLE);
pageMain.setVisibility(View.GONE);
pageRight.setVisibility(View.GONE);
}else if (mPageNumber==1){
pageLeft.setVisibility(View.GONE);
pageMain.setVisibility(View.VISIBLE);
pageRight.setVisibility(View.GONE);
}else if (mPageNumber==2){
pageLeft.setVisibility(View.GONE);
pageMain.setVisibility(View.GONE);
pageRight.setVisibility(View.VISIBLE);
}
return rootView;
}
public int getPageNumber() {
return mPageNumber;
}
scroll_view_content.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- Dummy content. -->
<LinearLayout
android:id="#+id/pageLeft"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
style="?android:textAppearanceMedium"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:lineSpacingMultiplier="1.2"
android:text="AAA" />
</LinearLayout>
<LinearLayout
android:id="#+id/pageRight"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
style="?android:textAppearanceMedium"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:lineSpacingMultiplier="1.2"
android:text="CCC"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/pageMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#123456"
android:orientation="vertical" >
<TextView
android:id="#+id/textB"
style="?android:textAppearanceMedium"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lineSpacingMultiplier="1.2"
android:background="#654321"
android:text="BBB"/>
<LinearLayout
android:layout_below="#+id/textB"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<Button
android:id="#+id/btnLeft"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#00ffff"
android:text="A"/>
<Button
android:id="#+id/btnRight"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#ffff00"
android:text="B"/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
Thats simple really. You have to use the setCurrentItem(int) of the view pager class. The algorithm would be:
int currPage=1 //Points to second page in the viewpager
if left button clicked //listener for the button
2a. currPage--
2b. mPager.setCurrentItem(currPage) //pager is object of your viewpager class
if right button clicked //listener for the button
3a. currPage++
3b. mPpager.setCurrentItem(currPage)
Check out this link for for info.
I am currently having an issue with replacing a certain fragment within ViewPager with another. The fragment id like to replace is my "Departments" which has an Imagebutton id like to use to begin the replacement. I've tried to apply some suggestions from other similar questions (most of which were old and prior to the new api release which allows for nested fragments) and have had no success. Would using nested fragments be easier? I am new to android app development so any help would be great. Thanks in advance.
here is my FragmentAcitivty
public class ViewPagerStyle extends FragmentActivity {
private ViewPager mViewPager;
private ViewPagerAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();
setTab();
}
private void setUpView(){
mViewPager = (ViewPager) findViewById(R.id.viewPager);
adapter = new ViewPagerAdapter(getApplicationContext(),getSupportFragmentManager());
mViewPager.setAdapter(adapter);
mViewPager.setCurrentItem(0);
}
private void setTab(){
mViewPager.setOnPageChangeListener(new OnPageChangeListener(){
#Override
public void onPageScrollStateChanged(int position) {}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
switch(position){
case 0:
findViewById(R.id.first_tab).setVisibility(View.VISIBLE);
findViewById(R.id.second_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.third_tab).setVisibility(View.INVISIBLE);
break;
case 1:
findViewById(R.id.first_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.second_tab).setVisibility(View.VISIBLE);
findViewById(R.id.third_tab).setVisibility(View.INVISIBLE);
break;
case 2:
findViewById(R.id.first_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.second_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.third_tab).setVisibility(View.VISIBLE);
break;
}
}
});
}
}
FragmentPagerAdapter
public class ViewPagerAdapter extends FragmentPagerAdapter {
private Context _context;
public ViewPagerAdapter(Context context, FragmentManager fm) {
super(fm);
_context = context;
}
#Override
public Fragment getItem(int position) {
Fragment f = new Fragment();
switch(position){
case 0:
f=PubView.newInstance(_context);
break;
case 1:
f=MyView.newInstance(_context);
break;
case 2:
f=Departments.newInstance(_context);
break;
}
return f;
}
#Override
public int getCount() {
return 3;
}
}
Departments Fragment with button
public class Departments extends Fragment {
public static Fragment newInstance(Context context) {
Departments f = new Departments();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View root = (View) inflater.inflate(R.layout.activity_departments, null);
ImageButton engineeringButton = (ImageButton)root.findViewById(R.id.engineeringButton);
engineeringButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Fragment newFragment = Engineering.newInstance(null);
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.viewPager, newFragment).commit();
}
});
return root;
}
}
Also, here is my main.xml file which hosts the viewpager
<?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:background="#color/purple"
android:orientation="vertical" >
<TableLayout
style="#style/layout_f_w"
android:stretchColumns="*" >
<TableRow
android:id="#+id/tableRow1"
style="#style/layout_wrap"
android:background="#color/white" >
<!-- First Tab -->
<LinearLayout
android:id="#+id/first_text"
style="#style/layout_f_w"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
style="#style/text_title"
android:text="pubView"
android:textColor="#color/purple" />
</LinearLayout>
<!-- Second Tab -->
<LinearLayout
android:id="#+id/second_text"
style="#style/layout_f_w"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
style="#style/text_title"
android:gravity="center"
android:text="myView"
android:textColor="#color/purple" />
</LinearLayout>
<!-- Third Tab -->
<LinearLayout
android:id="#+id/third_text"
style="#style/layout_f_w"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
style="#style/text_title"
android:text="Dept."
android:textColor="#color/purple" />
</LinearLayout>
</TableRow>
</TableLayout>
<!-- Include Tab Indicator -->
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/indicator" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="450dp" />
<ImageButton
android:id="#+id/settingsButton"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="50dp"
android:background="#drawable/settings_button"
android:src="#drawable/settings_button" />
</LinearLayout>
One thing i am confused on is that I don't know which id to put into the first argument of transaction.replace(r.id.viewPager, newfragment)...Ive read that it needs the id of the container but when I use this I receive the runtime error from logcat:
04-13 21:41:48.680: E/AndroidRuntime(960): java.lang.IllegalArgumentException: No view found for id 0x7f0a0029 (com.pvcalendar:id/viewPager) for fragment Engineering{4089a730 #0 id=0x7f0a0029}
I think the point is to use a fragment as a container.
In your ViewPagerAdapter:
#Override
public Fragment getItem(int position) {
/*
* IMPORTANT: This is the point. We create a RootFragment acting as
* a container for other fragments
*/
if (position == 0)
return new RootFragment();
else
return new StaticFragment();
}
RootFragment layout should look like:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/root_frame" >
</FrameLayout>
And directly, you fill it with your first "real" fragment:
public class RootFragment extends Fragment {
private static final String TAG = "RootFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* Inflate the layout for this fragment */
View view = inflater.inflate(R.layout.root_fragment, container, false);
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
/*
* When this container fragment is created, we fill it with our first
* "real" fragment
*/
transaction.replace(R.id.root_frame, new FirstFragment());
transaction.commit();
return view;
}
}
Finally, you can replace fragments. For instance, inside your "real" fragment you could have a button:
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction trans = getFragmentManager()
.beginTransaction();
/*
* IMPORTANT: We use the "root frame" defined in
* "root_fragment.xml" as the reference to replace fragment
*/
trans.replace(R.id.root_frame, new SecondFragment());
/*
* IMPORTANT: The following lines allow us to add the fragment
* to the stack and return to it later, by pressing back
*/
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);
trans.commit();
}
});
I've developed an example application that shows a similar concept. You could replace a fragment inside a ViewPager without changing to a new Activity. The code is available in:
https://github.com/danilao/fragments-viewpager-example
I'm assuming you want the Engineering fragment to be on a completely new page, because you aren't using it in your ViewPagerAdapter. If that's the case, create a new Activity, with your Engineering fragment in the layout, and launch the Activity from the engineeringButton click.
The problem is you are trying to shove your Engineering fragment into the View hierarchy of R.layout.activity_departments, and there is (hopefully) no ViewPager in there, hence the error.