如何在安卓中使用一个新Fragment完全替换View Pager的视图

6

I have the following xml file:

  <android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

我有一个视图页面中包含三个片段。在其中一个片段中,我尝试使用以下代码启动一个新的片段:

FragmentTransaction trans = getFragmentManager()
                .beginTransaction();
        trans.replace(R.id.pager, new SubscriptionFragment());
        trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        trans.addToBackStack(null);

        trans.commit();

我能成功地替换ViewPager中现有的片段,但这并不符合我的目的。我想做的是不要替换已经存在于ViewPager中的现有片段,而是将ViewPager本身从视图中删除,并启动一个新的Fragment,使顶部标签不再可见且ViewPager消失在视图中。当我使用意图启动新活动时,这可以实现,但对于片段则无法实现。
public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, new MainFragment()).commit();
    }


}

MainFragment:

public class MainFragment extends Fragment {

    FragmentPagerAdapter adapterViewPager;
    ViewPager viewPager;
    String title[] = {"Services", "You", "History"};

    // TODO: Rename and change types and number of parameters
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        /* Inflate the layout for this fragment */
        View view = inflater.inflate(R.layout.fragment_view_pager, container, false);




        /*************************************/
        //CALLING HISTORY API

        //  loadSubscriptions();

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        ViewPagerAdapter mAdapter = new ViewPagerAdapter(getFragmentManager());

        ViewPager mPager = (ViewPager) getView().findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);
    }

    public static class ViewPagerAdapter extends FragmentPagerAdapter {
        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int num) {
            if (num == 0) {
                return new ServicesFragment();
            } else {
                return new HistoryFragment();
            }
        }

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

activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

</FrameLayout>

fragment_view_pager.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

在ServiceFragment中:我正在使用以下方式打开新的Fragment:
physiotherapyView.setOnClickListener(new View.OnClickListener() {





 @Override

        public void onClick(View view) {

            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.pager, new SubscriptionFragment());

            /*
             * 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();

        }

    });

ViewPager也在Fragment中吗? - Itzik Samara
@ItzikSamara 不,它在一个 Activity 内部! - user3458008
2个回答

1
以下是完整的代码,用于向ViewPager中添加或删除片段。由于这只是演示,我只使用了一个textView,并且每个添加的片段都有一个随机的颜色。单击按钮,您可以添加任意数量的片段。单击页面,您可以从ViewPager中将其删除。您可以通过向右或向左滑动来在ViewPager中移动从一个页面到另一个页面。

MainActivity.java

import android.graphics.Color;
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.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.Random;

public class MainActivity extends FragmentActivity {

    private MyPagerAdapter mpg;
    private ArrayList<MyFragment> fragmentlist = new ArrayList<>();
    public FragmentManager fmr    = getSupportFragmentManager();

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

        final ViewPager pager  = (ViewPager) findViewById(R.id.viewPager);
        mpg = new MyPagerAdapter(fmr,fragmentlist);
        pager.setAdapter(mpg);

        for (int q = 0; q < 5; q++) {
            int r = new Random().nextInt(100) + 155;
            int g = new Random().nextInt(100) + 155;
            int b = new Random().nextInt(100) + 155;
            fragmentlist.add(MyFragment.newInstance(q, "Page number: " + (q + 1), Color.rgb(r, g, b)));
            mpg.notifyDataSetChanged();
        }

        Button  B1 = (Button) findViewById(R.id.button);
        B1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int r = new Random().nextInt(100) + 155;
                int g = new Random().nextInt(100) + 155;
                int b = new Random().nextInt(100) + 155;
                int count = mpg.getCount();
                fragmentlist.add(MyFragment.newInstance(count, "Page number: " + (count+1), Color.rgb(r, g, b)));
                mpg.notifyDataSetChanged();

            }
        });
    }

    public void delete(int pos) {

        int i = 0;
        while (i <= fragmentlist.size()) {
            if (pos == fragmentlist.get(i).getPosition()) break;
            i++;

        }

        fragmentlist.remove(i);
        mpg.notifyDataSetChanged();
    }

    public class MyPagerAdapter extends FragmentStatePagerAdapter {

        private ArrayList<MyFragment> fragmentList;
        public MyPagerAdapter(FragmentManager fm, ArrayList<MyFragment> f) {
            super(fm);
            this.fragmentList = f;
        }

        @Override
        public Fragment getItem(int pos) {
            return fragmentlist.get(pos);
        }

        @Override
        public int getCount() {
            return fragmentlist.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }
}

MyFragment.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.util.List;

public class MyFragment extends Fragment {

    int pos;

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.f_1, container, false);
        pos = getArguments().getInt("num");
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.v("MainActivity", "Deleting at pos - " + pos);
                MainActivity activity = (MainActivity) getActivity();
                activity.delete(pos);
            }
        });

        TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
        FrameLayout fl = (FrameLayout) v.findViewById(R.id.frame_layout);
        tv.setText(getArguments().getString("msg"));
        fl.setBackgroundColor(getArguments().getInt("colour"));
        return v;
    }

    public int getPosition() {
        return pos;
    }

    public static MyFragment newInstance(int num,String text,int clr) {

        MyFragment f = new MyFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);
        b.putInt("colour", clr);
        b.putInt("num",num);
        f.setArguments(b);
        return f;
    }
}

而且还有XML文件,

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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.example.shakthivels.assingment10.MainActivity"
    android:id="@+id/r_v"
    >

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ADD a fragment"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

f_1.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:id="@+id/av"
     >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/frame_layout">

        <TextView
            android:id="@+id/tvFragFirst"
            android:layout_width="203dp"
            android:layout_height="127dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:textSize="26sp"
            android:text="TextView"
            android:layout_gravity="center"
            android:textColor="#000000" />

    </FrameLayout>
</RelativeLayout>

已存在的片段1 新添加到视图页中的片段2


0

不要在 FrameLayout 中添加 ViewPager。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

</FrameLayout>

在这个布局中添加一个包含ViewPager的Fragment,并在你的MainActivity中添加FragmentTransaction。
    public class MainActivity extends FragmentActivity {


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, new MainFragment()).commit();

在这里,MainFragment 包含 ViewPager, 现在你可以使用 FragmentTransaction 替换整个布局中的 viewPager。


我已经收到了, 请检查答案是否合适。 - Abhishek
我不明白你想说什么。你的意思是我需要创建一个新类并扩展FragmentActivity。然后将viewPager放在Fragment而不是Activity中? - user3458008
你的Activity只会有一个FrameLayout,而一个单独的Fragment将包含ViewPager。 - Abhishek
谢谢您的建议。我会尝试一下! - user3458008
将代码中的 trans.replace(R.id.pager, new SubscriptionFragment()); 修改为 trans.replace(R.id.frame_layout, new SubscriptionFragment()); - Abhishek
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接