Fragment基本使用(三)——与Activity之间传递数据

本文介绍了Android应用开发中Fragment与Activity之间的数据交互方法。包括Fragment向Activity传递数据的具体实现步骤,以及Activity向Fragment传递数据的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Fragment向Activity传递数据

1,Fragment
在Fragment中定义一个接口,然后在onAttach(Activity activity)方法中取得这个接口的实现。

/**
 * Created by chourongqishi on 16/9/21.
 */
public class FirstFragment extends Fragment {

    private TransDataToActivityListener listener;

    public interface TransDataToActivityListener {
        public void setDatas(String datas);
    }

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

        View view = inflater.inflate(R.layout.fragment_first, container, false);
        listener.setDatas("向Activity传递数据");
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        try {
            listener = (TransDataToActivityListener) context;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
    }
}

2,Activity接收数据
Activity中实现Fragment定义的接口,然后取得数据

public class MainActivity extends FragmentActivity implements FirstFragment
        .TransDataToActivityListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //创建要添加的Fragment对象
        FirstFragment firstFragment = new FirstFragment();
        //获取Fragment管理器
        FragmentManager manager = getSupportFragmentManager();
        //获取事物管理器
        FragmentTransaction transaction = manager.beginTransaction();
        //添加Fragment
        transaction.add(R.id.fl_container, firstFragment);
        //提交事物
        transaction.commit();

    }

    /**
     * 实现Fragment中的接口,获取数据
     *
     * @param datas
     */
    @Override
    public void setDatas(String datas) {
        Toast.makeText(this, datas, Toast.LENGTH_SHORT).show();
    }
}

二、Activity向Fragment传递数据

1,Activity:

/**
     * 实现Fragment中的接口,获取数据
     *
     * @param datas
     */
    @Override
    public void setDatas(String datas) {
        //获取Fragment管理器
        FragmentManager manager = getSupportFragmentManager();
        //获取事物管理器
        FragmentTransaction transaction = manager.beginTransaction();
        //创建一个新Fragment对象
        NewFragment newFragment = new NewFragment();
        //添加数据
        Bundle bundle = new Bundle();
        bundle.putString("datas", datas);
        //向Fragment传递数据
        newFragment.setArguments(bundle);
        //替换Fragment
        transaction.replace(R.id.fl_container, newFragment);
        //将上一个Fragment加入回退栈
        transaction.addToBackStack(null);
        //提交事物
        transaction.commit();

    }

2,Fragment接收数据

/**
 * Created by chourongqishi on 16/9/21.
 */
public class NewFragment extends Fragment {
    private TextView tvShowDatas;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
    Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_new,container,false);
        tvShowDatas = (TextView) view.findViewById(R.id.tv_show_datas);
        Bundle bundle = getArguments();
        String datas = bundle.getString("datas");
        tvShowDatas.setText(datas);

        return view;
    }
}
### 使用ViewModel在Activity之间传递数据 为了实现`Activity`之间的数据共享,可以通过创建一个继承自`ViewModel`的类来保存和管理UI相关的数据。此方法允许不同组件(如多个`Activity`或它们所含有的`Fragment`)访问相同的`ViewModel`实例。 #### 创建并配置ViewModel 定义一个名为`SharedViewModel`的类用于存储要跨活动共享的信息: ```kotlin import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class SharedViewModel : ViewModel() { private val _sharedMessage = MutableLiveData<String>() val sharedMessage: LiveData<String> get() = _sharedMessage fun setSharedMessage(message: String) { _sharedMessage.value = message } } ``` 上述代码展示了如何封装一条消息字符串作为可观察的数据源[^1]。 #### 在第一个Activity中设置ViewModel 当从第一个`Activity`准备向第二个发送信息时,初始化这个公共视图模型,并调用相应的方法更新其内部状态: ```kotlin // Inside FirstActivity.kt val model: SharedViewModel by viewModels() button.setOnClickListener { model.setSharedMessage("Hello from Activity One!") startActivity(Intent(this, SecondActivity::class.java)) } ``` 这里利用Kotlin合成器简化了获取`ViewModel`的过程;点击按钮后不仅设置了待传输的消息还启动了新的界面。 #### 接收端——第二Activity读取ViewModel中的数据 新打开的目标页面同样需要关联到同一个`ViewModel`对象上来提取之前设定好的值: ```kotlin // Within SecondActivity.kt val model: SharedViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Observe the live data and update UI accordingly. model.sharedMessage.observe(this@SecondActivity, Observer { message -> textView.text = message }) } ``` 通过这种方式,在两个独立运行的应用程序单元间实现了高效而简洁的数据交换机制[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值