博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android在片段之间传递数据
阅读量:2533 次
发布时间:2019-05-11

本文共 7356 字,大约阅读时间需要 24 分钟。

In this tutorial, we’ll be developing an application that contains TabLayout, ViewPager and Fragments. We’ll implement a functionality that passes data from one Fragment to the other fragment.

在本教程中,我们将开发一个包含TabLayout,ViewPager和Fragments的应用程序。 我们将实现将数据从一个Fragment传递到另一个Fragment的功能。

Android在片段之间传递数据 (Android Passing Data between Fragments)

Intents are only usable for sending data on an Activity level. To pass data between fragments we need to create our own interfaces. The flow to send a String data from one Fragment to another is shown below.

意图仅可用于在活动级别上发送数据。 为了在片段之间传递数据,我们需要创建自己的接口。 下面显示了将String数据从一个Fragment发送到另一个Fragment的流程。

Let’s get started with the implementation of the above flow.

让我们开始执行上述流程。

Android在片段项目结构之间传递数据 (Android Passing Data between Fragments Project Structure)

The xml layout for the MainActivity.java class is given below.

MainActivity.java类的xml布局如下。

The styles for the TabLayout and ToolBar are defined in the styles.xml file as shown below.

TabLayout和ToolBar的样式在styles.xml文件中定义,如下所示。

The ViewPagerAdapter.java is where the Fragments are initialised. The code is given below.

ViewPagerAdapter.java是片段的初始化位置。 代码如下。

public class ViewPagerAdapter extends FragmentPagerAdapter {    public ViewPagerAdapter(FragmentManager fm) {        super(fm);    }    @Override    public Fragment getItem(int position) {        Fragment fragment = null;        if (position == 0) {            fragment = new FragmentOne();        } else if (position == 1) {            fragment = new FragmentTwo();        }        return fragment;    }    @Override    public int getCount() {        return 2;    }    @Override    public CharSequence getPageTitle(int position) {        String title = null;        if (position == 0) {            title = "Tab-1";        } else if (position == 1) {            title = "Tab-2";        }        return title;    }}

FragmentOne would be sending the data entered in EditText to FragmentTwo.

FragmentOne会将在EditText中输入的数据发送到FragmentTwo。

The xml layout for fragment_one.xml is given below.

下面给出fragment_one.xml的xml布局。

The xml layout for fragment_two.xml is given below.

以下给出fragment_two.xml的xml布局。

The code for FragmentOne.java class is given below.

FragmentOne.java类的代码如下。

package com.journaldev.passingdatabetweenfragments;import android.content.Context;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.EditText;public class FragmentOne extends Fragment {    SendMessage SM;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View rootView = inflater.inflate(                R.layout.fragment_one, container, false);        return rootView;    }    @Override    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {        super.onViewCreated(view, savedInstanceState);        Button btnPassData = (Button) view.findViewById(R.id.btnPassData);        final EditText inData = (EditText) view.findViewById(R.id.inMessage);        btnPassData.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                SM.sendData(inData.getText().toString().trim());            }        });    }    interface SendMessage {        void sendData(String message);    }    @Override    public void onAttach(Context context) {        super.onAttach(context);        try {            SM = (SendMessage) getActivity();        } catch (ClassCastException e) {            throw new ClassCastException("Error in retrieving data. Please try again");        }    }}

The Custom Interface namely SendMessage is initialised in the onAttach method above. This interface would be implemented in the MainActivity.java that we’ll be seeing shortly.

自定义接口(即SendMessage )在上面的onAttach方法中初始化。 该接口将在我们即将看到的MainActivity.java中实现。

The code for FragmentTwo.java class is given below.

FragmentTwo.java类的代码如下。

package com.journaldev.passingdatabetweenfragments;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;public class FragmentTwo extends Fragment {    TextView txtData;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View rootView = inflater.inflate(                R.layout.fragment_two, container, false);        return rootView;    }    @Override    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {        super.onViewCreated(view, savedInstanceState);        txtData = (TextView)view.findViewById(R.id.txtData);    }    protected void displayReceivedData(String message)    {        txtData.setText("Data received: "+message);    }}

The displayReceivedData() would be called on the instance of FragmentTwo.java from inside the Custom Interface’s method inside the MainActivity.java as shown below.

如下所示,将从MainActivity.java内的Custom Interface的方法内部的FragmentTwo.java实例上调用displayReceivedData()

package com.journaldev.passingdatabetweenfragments;import android.support.design.widget.TabLayout;import android.support.v4.view.ViewPager;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.Toolbar;public class MainActivity extends AppCompatActivity implements FragmentOne.SendMessage{    TabLayout tabLayout;    ViewPager viewPager;    ViewPagerAdapter viewPagerAdapter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        viewPager = (ViewPager) findViewById(R.id.viewPager);        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());        viewPager.setAdapter(viewPagerAdapter);        tabLayout = (TabLayout) findViewById(R.id.tabs);        tabLayout.setupWithViewPager(viewPager);    }    @Override    public void sendData(String message) {        String tag = "android:switcher:" + R.id.viewPager + ":" + 1;        FragmentTwo f = (FragmentTwo) getSupportFragmentManager().findFragmentByTag(tag);        f.displayReceivedData(message);    }}

The sendData() method in the above code gets triggered as soon as the Button in FragmentOne is pressed. We fetch the FragmentTwo that was already initialised in ViewPagerAdapter using the method findFragmentByTag.

sendData()按下FragmentOne中的Button,就会触发上述代码中的sendData()方法。 我们使用findFragmentByTag方法获取在ViewPagerAdapter中已经初始化的FragmentTwo。

The output of the above application in action is given below.

下面给出了上面应用程序的输出。

This brings an end to this tutorial. You can download the final Android PassingDataBetweenFragments Project from the link below.

本教程到此结束。 您可以从下面的链接下载最终的Android PassingDataBetweenFragments项目

Reference:

参考:

翻译自:

转载地址:http://luqzd.baihongyu.com/

你可能感兴趣的文章
【转】how can i build fast
查看>>
null?对象?异常?到底应该如何返回错误信息
查看>>
django登录验证码操作
查看>>
(简单)华为Nova青春 WAS-AL00的USB调试模式在哪里开启的流程
查看>>
图论知识,博客
查看>>
[原创]一篇无关技术的小日记(仅作暂存)
查看>>
20145303刘俊谦 Exp7 网络欺诈技术防范
查看>>
原生和jQuery的ajax用法
查看>>
iOS开发播放文本
查看>>
20145202马超《java》实验5
查看>>
JQuery 事件
查看>>
main(argc,argv[])
查看>>
在线教育工具—白板系统的迭代1——bug监控排查
查看>>
121. Best Time to Buy and Sell Stock
查看>>
hdu 1005 根据递推公式构造矩阵 ( 矩阵快速幂)
查看>>
安装php扩展
查看>>
百度移动搜索主要有如下几类结果构成
查看>>
Python爬虫面试题170道:2019版【1】
查看>>
JavaBean规范
查看>>
第四阶段 15_Linux tomcat安装与配置
查看>>