简体   繁体   中英

Android navigate one fragment to another is working but , cannot see other fragment's background

I try to navigate one fragment to another. In here I use a button to do this process . When I run this , I get a blank screen at the end.

These are my steps,

MainActivity.java

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.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class MainActivity extends FragmentActivity {

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

        final int page=2;

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

        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        pager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (pager.getCurrentItem()==page) {
                    return  true;
                }
                return false;
            }
        });

    }

    private class MyPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int pos) {
            switch(pos) {

                case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
                case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
                case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
                default: return ThirdFragment.newInstance("ThirdFragment, Default");
            }
        }

        @Override
        public int getCount() {
            return 4;
        }

    }
}

I wanted navigate third fragment to fourth one.

activity_main.xml

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

third_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_red_light" >

<TextView
    android:id="@+id/tvFragThird"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:textSize="26dp"
    android:text="TextView" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:id="@+id/printButton"
        android:text="Next"/>

</RelativeLayout>

ThirdFragment.java

public class ThirdFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.third_frag, container, false);

        TextView tv = (TextView) v.findViewById(R.id.tvFragThird);
        tv.setText(getArguments().getString("msg"));
        Button button=(Button)v.findViewById(R.id.printButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FourthFragment fourthFragment=new FourthFragment();
                Bundle bundle=new Bundle();
                bundle.putInt(String.valueOf(FirstFragment.newInstance("Terance")),1);
                fourthFragment.setArguments(bundle);

                FragmentManager fragmentManager=getFragmentManager();

                FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.replace(R.id.viewPager, fourthFragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });

        return v;
    }

    public static ThirdFragment newInstance(String text) {

        ThirdFragment f = new ThirdFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }

}

fourth_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_dark">

    <TextView
        android:id="@+id/tvFragFourth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />

</RelativeLayout>

FourthFragment.java

public class FourthFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fourth_frag, container, false);

        TextView tv = (TextView) v.findViewById(R.id.tvFragFourth);
        tv.setText("Fourth Fragment");

        return v;
    }

    public static FourthFragment newInstance(String text) {

        text="Terance";
        FourthFragment f = new FourthFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }

}

There are four fragments classes and I have mentioned only two which are used for the purpose. when come to the third fragment, cannot swipe this to left or right. Then I use a button to go to fourth fragment. But it is not working .

Have any ideas about this ?

Thank you.

I think You have four fragments, but what you did in MyPagerAdapter is

 @Override
    public Fragment getItem(int pos) {
        switch(pos) {

            case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
            case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
            case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
            default: return ThirdFragment.newInstance("ThirdFragment, Default");
        }
    }

you only added 3 fragment in switch case that is why you are not able to navigate from third fragment to fourth fragment, I think what you should do is

 @Override
    public Fragment getItem(int pos) {
        switch(pos) {

            case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
            case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
            case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
            case 3: return FourthFragment.newInstance("FourthFragment, Instance 1");
            default: return ThirdFragment.newInstance("ThirdFragment, Default");
        }
    }

You are replacing the Fourth Fragment with R.id.viewPager, which is wrong.

You should call ViewPager method setcurrentItem(id) to change fragment inside View pager. This is desirable way of navigation because we are using View Pager.

In your Activity, make a method :

public void setCurrentItem(int which) {
    if(viewpager != null && which >= 0 && which <= 4) {
        viewpager.setCurrentItem(which);
    }
}

Call this method from ThirdFragment.java :

button.setOnClickListener(new View.OnClickListener() {
    if(getActivity() != null) {
        getActivity().setCurrentItem(3); // fourth fragment index is 3
    }
}

Better override the onPageSelected() method of Viewpager to give the correct position of page.

    public void onPageSelected(int position) {
        //set your page here which gives current page position
    }
private class MyPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int pos) {
        switch(pos) {

            case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
            case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
            case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
            default: return ThirdFragment.newInstance("ThirdFragment, Default");
        }
    }

    @Override
    public int getCount() {
        return 4;
    }

}

In the above code, in pager adapter, also defined case of fourth adapter, ie

case 3: return FourthFragment.newInstance("FourthFragment, Instance 1");

And second problem is that by clicking button you are not able to go to FourthFragment using this code...

Button button=(Button)v.findViewById(R.id.printButton);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FourthFragment fourthFragment=new FourthFragment();
            Bundle bundle=new Bundle();
            bundle.putInt(String.valueOf(FirstFragment.newInstance("Terance")),1);
            fourthFragment.setArguments(bundle);

            FragmentManager fragmentManager=getFragmentManager();

            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.viewPager, fourthFragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });

In place of the replacing fragment at android.support.v4.view.ViewPager,

transaction.replace(R.id.viewPager, fourthFragment);

use FrameLayout.

transaction.replace(R.id.framelayout, fourthFragment);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM