目录
Activity -> Activity
Activity -> Fragment
Fragment -> Activity
Activity -> Service
实现小例子:
从MainActivity跳转并传值到Activity2,之后从Activity2再传值回到MainActivity
activity_main的布局:
activity2的布局:
MainActivity代码(写有备注):创建Bundle对象,向其里面加入需要传递的值,注意值的类型,添加完毕之后,由intent将该bundle对象传递即可。
注意一下,如果另一个activity2返回来用的是setResult()函数,那么在MainActivity中传值是需要使用 startActivityForResult函数,如果单纯的使用startActivity函数进行跳转,会导致MainActivity中onActivityResult不会执行。
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取控件
Button button = findViewById(R.id.btn_send);
textView = findViewById(R.id.textview_back);
button.setOnClickListener(this);
}
//得到传回的数据
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case 1:
Bundle bundle_back=data.getExtras();
String str=bundle_back.getString("b");
textView.setText(str);
break;
}
}
//按钮点击事件
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_send:
Bundle bundle = new Bundle();
bundle.putString("name","玛丽");
bundle.putInt("age",15);
Intent intent = new Intent(MainActivity.this,Activity2.class);
intent.putExtras(bundle);
startActivityForResult(intent,0);
break;
}
}
}
Activity2代码:在获传递过来值的时候我一直获取为空值,感觉很奇怪,之后发现是有两点导致的
1.被传递到的这个Activity中对Intent的操作,不要写成 Intent intent = new Intent();,这样只是会重新在该页面创建了一个新的对象,而需要写成 Intent intent = getIntent();去获取前面传递的值。
2.对于获取需要传回的content的放置位置也很关键,不可以放在onCreate()函数里面获取,这样会导致只会在初始化的时候执行一次,之后写入数据后是不会再执行的,会导致传回去的值一直为空。
public class Activity2 extends Activity implements View.OnClickListener {
String name,content;
int age;
EditText editText;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
//获取控件
TextView textView = findViewById(R.id.text_receive);
editText = findViewById(R.id.edit_back);
Button button = findViewById(R.id.btn_back);
//接收传来的值并显示
Intent intent = getIntent();
name = intent.getStringExtra("name");
age = intent.getIntExtra("age",-1);
textView.setText("名字:"+name+",年龄:"+age);
button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_back:
//返回值
content = editText.getText().toString().trim();
Intent intent_back = new Intent(Activity2.this,MainActivity.class);
intent_back.putExtra("b",content);
setResult(1,intent_back);
finish();
break;
}
}
}
执行效果如下:
实现小例子:
从Activity跳转并传值到Fragment
activity_main的布局:
fragment_test的布局:
MainActivity代码(写有备注):注意需要将fragment与activity进行绑定。
public class MainActivity extends AppCompatActivity {
private EditText edit_input;
private Button btn_send;
private String inputContent;
private FragmentManager manager;
private FragmentTransaction transaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取控件
edit_input = findViewById(R.id.edit_input);
btn_send = findViewById(R.id.btn_send);
//fragment与activity进行绑定
manager = getSupportFragmentManager();
transaction = manager.beginTransaction();
transaction.add(R.id.contentLayout, new FragmentTest());
transaction.commit();
//按钮点击事件
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
inputContent = edit_input.getText().toString().trim();
FragmentTest fragmentTest = new FragmentTest();
Bundle bundle = new Bundle();
bundle.putString("content", inputContent);
fragmentTest.setArguments(bundle);
manager = getSupportFragmentManager();
transaction = manager.beginTransaction();
transaction.replace(R.id.contentLayout, fragmentTest);
transaction.commit();
}
});
}
}
在从Activity -> Fragment传值中,困扰了我很久,我使用FragmentManager manager = getFragmentManager(); 再使用(transaction为FragmentTransaction的对象)
transaction.add(R.id.contentLayout, new FragmentTest());
该句下方会出现红线。最后成功解决使用的方法是FragmentManager manager =getSupportFragmentManager(); 上方导入的为
import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction;具体的原因目前我还是不太了解。
FragmentTest代码:
public class FragmentTest extends Fragment {
private TextView tvContent;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, null);
tvContent = view.findViewById(R.id.tvContent);
//获取activity传送过来的值
Bundle bundle = getArguments();
if (bundle != null) {
tvContent.setText(bundle.getString("content"));
}
return view;
}
}
运行结果如图:
activity_main的布局:
fragment_test的布局:
MainActivity代码(写有备注):
public class MainActivity extends Activity implements FragmentTest.CallBackValue {
private TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
//activity与fragment进行绑定
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.contents, new Fragmen1());
transaction.commit();
}
//传递值
@Override
public void SendMessageValue(String content) {
tv1.setText(content);
}
}
FragmentTest代码:
public class FragmentTest extends Fragment{
private Button btn1;
private EditText et1;
CallBackValue callBackValue;
//fragment与activity产生关联是回调这个方法
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callBackValue =(CallBackValue) getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout1, container, false);
//获取控件
btn1 = (Button) view.findViewById(R.id.btn_send);
et1 = (EditText) view.findViewById(R.id.edit_test);
//点击事件
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String content = et1.getText().toString().trim();
callBackValue.SendMessageValue(content);
}
});
return view;
}
//定义一个回调接口
public interface CallBackValue{
public void SendMessageValue(String content);
}
}
运行结果截图:
activity_main的布局如上。
方法一:使Activity实现implements ServiceConnection ,实现onServiceConnected函数。创ServiceTest.Binder的对象,通过这个对象来实现通信传值。
MainActivity代码(写有备注):
public class MainActivity extends AppCompatActivity implements ServiceConnection {
private EditText edit_input;
private Button btn_send;
private String inputContent;
public ServiceTest.Binder binder = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取控件
edit_input = findViewById(R.id.edit_input);
btn_send = findViewById(R.id.btn_send);
//绑定服务
Intent intent = new Intent(MainActivity.this,ServiceTest.class);
bindService(intent,this, Context.BIND_AUTO_CREATE);
//按钮点击事件
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
inputContent = edit_input.getText().toString().trim();
//通过 binder 对象来和 Service 进行通信
if(binder != null)
binder.sendData(inputContent);
}
});
}
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
binder = (ServiceTest.Binder)iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(this);
}
}
ServiceTest代码(写有备注):
public class ServiceTest extends Service {
String data;
public ServiceTest(){
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new Binder();
}
public class Binder extends android.os.Binder{
public void sendData(String data){
ServiceTest.this.data = data;
Toast.makeText(ServiceTest.this, "哈哈哈"+data, Toast.LENGTH_SHORT).show();
}
}
}
运行如下:
方法二:使用Intent,适用于传送少量的数据。
MainActivity代码(写有备注):
public class MainActivity extends AppCompatActivity {
private EditText edit_input;
private Button btn_send;
private String inputContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取控件
edit_input = findViewById(R.id.edit_input);
btn_send = findViewById(R.id.btn_send);
//绑定服务
Intent intent = new Intent(MainActivity.this,ServiceTest.class);
//按钮点击事件
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
inputContent = edit_input.getText().toString().trim();
intent.putExtra("test",inputContent);
startService(intent);
}
});
}
}
ServiceTest代码(写有备注):
public class ServiceTest extends Service {
String data;
public ServiceTest(){
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//得到Activity传的数据
data = intent.getStringExtra("test");
Toast.makeText(ServiceTest.this, "传过来的数据"+data, Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
}
运行截图: