方法一:把需要传递的类实现Serilziable接口!
(1)MainActivity文件:
package com.example.myapplication_1;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button =(Button)findViewById(R.id.button_1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
UserInfo userInfo =new UserInfo();
userInfo.userName = "二狗";
userInfo.age = 111;
userInfo.gender = "男";
intent.putExtra("userInfo",userInfo); //将userInfo这个实例化对象传递给该方法。
startActivity(intent);
}
});
}
}
(2)MainActivity2文件:
package com.example.myapplication_1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView textView = (TextView)findViewById(R.id.tv_2);
UserInfo userInfo = (UserInfo) getIntent().getSerializableExtra("userInfo");
textView.setText(userInfo.userName+","+userInfo.age+","+userInfo.gender);
}
}
方法二:把需要传递的类实现Parceable接口!