android动态替换Fragment向下传递数据

以前传递数据都是使用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"));



android动态替换Fragment向下传递数据

上一篇:手机APP的测试点


下一篇:appium自动化框架项目实战1——app初次使用引导页