在ViewPager中实现两个fragment之间点击跳转与几种数据传递的方法

来源:互联网 发布:算法导论pdf百度云 编辑:程序博客网 时间:2024/05/17 21:53

一、ViewPager+fragment可以实现界面的滑动与点击跳转,结合ViewPager,Fragment之间的滑动很简单,下面首先我们来看看如何实现fragment结合ViewPager的使用:

图片效果

这是程序主界面向左滑动会滑到第二个fragment上这里写图片描述

这里写代码片:这是MainActivity布局,很简单<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.viewpagertest.MainActivity">    <android.support.v4.view.ViewPager        android:id="@+id/viewPager"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_weight="3"        android:flipInterval="30"        >    </android.support.v4.view.ViewPager></LinearLayout>
这里写代码片:主活动的代码,声明一个ViewPager,为其设置Adapter,将数据传入Adapter,这里的的数据是用一个List集合装载的,里面就是Fragment实例,所以除了写主活动的布局之外还需写两个碎片的布局和实例public class MainActivity extends AppCompatActivity {    private ViewPager viewPager;    private List<Fragment>fragments ;    Fragment1 fragment1;    private String name;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        viewPager = (ViewPager)findViewById(R.id.viewPager);        fragments = new ArrayList<>();        fragment1 = new Fragment1();        fragments.add(fragment1);        Fragment2 fragment2 = new Fragment2();        fragments.add(fragment2);        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(),fragments);        viewPager.setAdapter(fragmentAdapter);    }
这里写代码片:Fragment1代码:重写onCreateView方法,注册点击事件public class Fragment1 extends Fragment implements View.OnClickListener {    private Button bt_first_fragment;    private View view;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        view = inflater.inflate(R.layout.fragment1_layout,container,false);        bt_first_fragment = (Button) view.findViewById(R.id.bt_first_fragment);        bt_first_fragment.setOnClickListener(this);        return view;    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.bt_first_fragment:            Toast.makeText(getContext(),"点击第一个Fragment",Toast.LENGTH_SHORT).show();             break;
这里写代码片:Fragment1的布局<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent"><Button    android:background="@color/colorPrimaryDark"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:text="点击第一个fragment"    android:id="@+id/bt_first_fragment"/></LinearLayout>
这里写代码片:Fragment2代码:public class Fragment2 extends Fragment implements View.OnClickListener {    Button bt_second_fragment;    MainActivity mainActivity;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragment2_layout,container,false);        bt_second_fragment = (Button)view.findViewById(R.id.bt_second_fragment);        bt_second_fragment.setOnClickListener(this);        return view;    }    @Override    public void onAttach(Context context) {        super.onAttach(context);        mainActivity = (MainActivity) context;    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.bt_second_fragment:                Toast.makeText(getContext(),"123",Toast.LENGTH_SHORT).show();        }    }
这里写代码片:Fragment2布局<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent"><Button    android:background="@color/colorAccent"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:id="@+id/bt_second_fragment"    android:text="点击第二张fragment"/></LinearLayout>

以上是实现滑动的效果,现在我想实现的是从Fragment1中直接点击进入第二个Fragment我们应该怎么去实现呢?方法有很多种,我选择的是接口回调的办法,这也是比较常用的方法,用法如下:

我要在碎片里面点击那么具体的点击事件需要写在碎片里,所以接口的注册就要在他的宿主Activity里了也就是MainActivity

1在MainActivity中随便在哪注册一个接口,里面写一个抽象方法
这里写代码片public interface Fragment2Fragment{        void switchFragment(ViewPager viewPager);    }

2 在MainActivity中声明一个全局的接口对象变量并为其生成set()方法,并对该接口对象进行判断是否为空;

这里写代码片  public void setFragment2Fragment(Fragment2Fragment fragment2Fragment) {        this.fragment2Fragment = fragment2Fragment;}public void forSkip(){        if(fragment2Fragment != null){            fragment2Fragment.gotoFragment(viewPager);        }    }

3接口定义好之后,哪个地方要用就在哪个地方实现,比如说我们这个Demo里我要在碎片1里面点击Button进入碎片2,那就在点击事件的逻辑里面实现,具体步骤一般来说:在碎片1中获得宿主Activity的实例,然后用该实例的set接口方法,里面传接口对象,最后实现抽象方法,代码如下:

这里写代码片final MainActivity mainActivity = (MainActivity)getActivity();                mainActivity.setFragment2Fragment(new MainActivity.Fragment2Fragment() {                    @Override                    public void gotoFragment(ViewPager viewPager) {                        viewPager.setCurrentItem(1);//选择跳到哪个碎片上                          }                });                 mainActivity.forSkip();

以上解决了点击fragment之间跳转的问题,接下来我们今天最后一个问题就是如何在两个碎片之间传递数据呢?我这里试了两个方法,还有其他的一些就不具体说了

方法1:在宿主Activity里面写get(),set()方法比如我们想点击时传递一个字符串

这里写代码片:在宿主Activity上写    public void setStr(String name){        this.name = name;    }    public String getStr(){        return name;    }
这里写代码片:在碎片1的点击事件中添加如下                       mainActivity.setStr("123");
这里写代码片 String str = ((MainActivity) getActivity()).getStr();

这样就可以获得从碎片1中传来的字符串了

方法2:使用Handler,直接在碎片1的点击事件中发送消息然后在碎片2中接收消息具体如下:

这里写代码片:碎片1中的点击事件里面添加  Message message = new Message();  message.what = 0;  message.obj = "123";  mHandler.sendMessage(message);
这里写代码片:碎片类中添加public static final Handler mHandler = new Handler(){        public void handleMessage(Message message){            switch (message.what){                case 0:                    String obj = message.obj.toString();                    Log.d("Tag===========",obj);            }        }    };
阅读全文
0 0