以前传递数据都是使用Intent进行传递,但是intent是跳转,我们这个是动态替换 所以刚开始也是一脸懵逼,百度也百度不到,就自己慢慢摸索出来了:
话不多说,直接上代码:(主要核心代码加粗)
package com.smartgentechnology;import android.content.Intent;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.TextView; public class HomePage extends AppCompatActivity implements View.OnClickListener {//动态替换碎片 private TextView tab1, tab2, tab3, user; private String jurisdiction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_homepage); Intent intentHome = getIntent(); jurisdiction = intentHome.getStringExtra("importid"); String username = intentHome.getStringExtra("importname"); user = findViewById(R.id.home_name); user.setText(username); initView();//初始化数据 } private void initView() { tab1 = findViewById(R.id.set); tab2 = findViewById(R.id.statement); tab3 = findViewById(R.id.repaire); tab1.setOnClickListener(this); tab2.setOnClickListener(this); tab3.setOnClickListener(this); tab1.setSelected(true); replaceFragment(new BasicSetting(), jurisdiction); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.set: selected(); tab1.setSelected(true); replaceFragment(new BasicSetting(), jurisdiction); break; case R.id.statement: selected(); tab2.setSelected(true); replaceFragment(new Report(), jurisdiction); break; case R.id.repaire: selected(); tab3.setSelected(true); replaceFragment(new RepairModule(), jurisdiction); break; } } private void replaceFragment(Fragment fragment, String uid) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.main_fragment, fragment); Bundle bundle = new Bundle();//使用Bundle传递数据 bundle.putString("msg", uid); fragment.setArguments(bundle); transaction.commit(); } private void selected() {//初始化是否选中的状态 tab1.setSelected(false); tab2.setSelected(false); tab3.setSelected(false); }} 在碎片中接收数据:
//获得窗体传递来的数据Bundle bundle= BasicSetting.this.getArguments();//显示传递来的数据String uid = bundle.getString("msg");//Log.i("chulaiba",bundle.getString("msg"));
原文地址:https://www.cnblogs.com/yh0409/p/10818582.html
时间: 2024-11-05 16:00:17