2

I'm trying to change the viewpager fragment by clicking on a button. I have 2 fragments(FragmentA,FragementB), each fragment has it's own xml file (fragement_a.xml, fragement_b.xml, and so on). i call ImageView object in FragementA and when i press that imageView object i want to load FragmentB. please help me to do it.

please find below code i used.

..\swipetabs\src\com\example\swipetabs\MainActivity.java

   package com.example.swipetabs;

import com.tabs.*;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends FragmentActivity implements TabListener {

    ActionBar action_bar;
    ViewPager viewPager;
    ImageView creditCards;
    Fragment fragement;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager=(ViewPager)findViewById(R.id.pager);

        viewPager.setAdapter(new MyAdoptor(getSupportFragmentManager()));

        action_bar=getActionBar();
        //action_bar.setBackgroundDrawable(d)
        action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        ActionBar.Tab tab1=action_bar.newTab();
        tab1.setText("Login");

        tab1.setTabListener(this);

        ActionBar.Tab tab2=action_bar.newTab();
        tab2.setText("Compare Now");
        tab2.setTabListener(this);

        ActionBar.Tab tab3=action_bar.newTab();
        tab3.setText("Search");
        tab3.setTabListener(this);

        action_bar.addTab(tab1);
        action_bar.addTab(tab2);
        action_bar.addTab(tab3);


    }

    public void switchToFragmentB(){
        viewPager.setCurrentItem(1);
     }

    @Override
    public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }


}


class MyAdoptor extends FragmentPagerAdapter
{

    public MyAdoptor(FragmentManager fm) {
        super(fm);
                // TODO Auto-generated constructor stub
    }

    @Override
    public Fragment getItem(int arg0) {
        // TODO Auto-generated method stub

        Fragment fragement=null;
        if(arg0==0)
        {
            fragement=new FragmentA();
        }
        if(arg0==1)
        {
            fragement=new FragmentB();
        }

        System.out.print("<><><><>");
        return fragement;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return 2;
    }

}

..\swipetabs\src\com\tabs\FragmentA.java

 import com.example.swipetabs.R;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import com.example.swipetabs.*;

    /**
     * A simple {@link android.support.v4.app.Fragment} subclass.
     * 
     */
    public class FragmentA extends Fragment implements OnClickListener{

        public FragmentA() {

            // 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_a, container, false);
            ImageView btnT = (ImageView)v.findViewById(R.id.imageView1);
            btnT.setOnClickListener(this);


            return inflater.inflate(R.layout.fragment_a, container, false);


        }

        public void onClick(View v) {
             /*When I click this button in my fragment, I'd like it to go to fragment B for example*/
            ((MainActivity)getActivity()).switchToFragmentB();


        }

..\swipetabs\src\com\tabs\FragmentB.java

package com.tabs;

import com.example.swipetabs.R;
import com.example.swipetabs.R.layout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 * 
 */
public class FragmentB extends Fragment {

    public FragmentB() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_b, container, false);
    }

}

fragement_a.xml

<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:background="#FFCC00"
    tools:context=".FragmentA" >

    <!-- TODO: Update blank fragment layout -->

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="205dp"
        android:src="@drawable/ic_launcher" />

</FrameLayout>

fragement_b.xml

<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"
    tools:context=".FragmentB" >

    <!-- TODO: Update blank fragment layout -->

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

AndroidManifestFile

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.swipetabs"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.swipetabs.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
VenushkaT
  • 1,152
  • 2
  • 18
  • 42

3 Answers3

5

Create one method in your MainActivity.java

public class MainActivity extends FragmentActivity implements TabListener {

       ///Your Code

       // Call This method From your Fragment's Button click.
       public void switchToFragmentB(){
          viewPager.setCurrentItem(1);
       }
       ///Your Code 
 }

How to call the method from Fragment?

public class FragmentA extends Fragment {

      /// Your Code

    public void onClick(View v) {

      ((MainActivity)getActivity()).switchToFragmentB();

    }


}

UPDATE:

In onCreateView() method Change your return statement to

return v; (True)

return inflater.inflate(R.layout.fragment_a, container, false); (Wrong)

Biraj Zalavadia
  • 27,124
  • 9
  • 56
  • 73
  • i have done the code again it doesnt work for me.could you please see my edited code.i have posted already what you have suggested.thank you – VenushkaT Feb 03 '14 at 07:00
  • i have done the code again it doesnt work for me.could you please see my edited code.i've already posted the Edited code.i have checked it by putting System.out.prinn(">>>) into public void onClick(View v) method when i press the image view logcat show me nothing.it means that when i press imageview it doesnt go inside Onclick method.. thank you – VenushkaT Feb 03 '14 at 07:15
0

You can try something like this:

public class TabPageAdapter extends FragmentPagerAdapter {

public TabPageAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int index) {

    switch (index) {
    case 0:
        // Top Rated fragment activity
        return new TopRatedFragment();
    case 1:
        // Games fragment activity
        return new GamesFragment();
    case 2:
        // Movies fragment activity
        return new MoviesFragment();
    }

    return null;
}

@Override
public int getCount() {
    // get item count - equal to number of tabs
    return 3;
}

}

//fragment class

public class TopRatedFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.frag1,
            container, false);

    return rootView;
}

}

poojagupta
  • 932
  • 2
  • 11
  • 24
0

Try this code, first make a Inteface -

public interface SwitchToFragmentB {
public void switchToFragmentB();

}

Now implement this interface to your main Activity-

public class MyActivity extends FragmentActivity implements SwitchToFragmentB {

@Override
public void switchToFragmentB() {
    viewPager.setCurrentItem(1);
}

}

Now in your fragment -

public class FragmentA extends Fragment implements View.OnClickListener {

@Override
public void onClick(View view) {
    SwitchToFragmentB switchToB = (SwitchToFragmentB) getActivity();
    switchToB.switchToFragmentB();
}

}

Hope this will Help -

Zia
  • 1,975
  • 2
  • 14
  • 14