-
Activity -> Activity
<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="传值"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textview_back"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:textSize="20sp"
android:text="默认值"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_send"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="@+id/text_receive"
android:layout_width="match_parent"
android:layout_height="100dp"
android:gravity="center"
android:text="默认值"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.339" />
<EditText
android:id="@+id/edit_back"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/text_receive"
app:layout_constraintVertical_bias="0.2" />
<Button
android:id="@+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="返回值"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edit_back" />
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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_input"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_margin="10dp"
android:hint="输入内容" />
<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="发送"
android:textSize="30sp" />
<LinearLayout
android:id="@+id/contentLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="默认值"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
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;
}
}
-
Fragment -> Activity
activity_main的布局:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/contents"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="默认值"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/edit_test"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="88dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_send" />
</androidx.constraintlayout.widget.ConstraintLayout>
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 -> Service
activity_main的布局如上。
方法一:使Activity实现implements ServiceConnection ,实现onServiceConnected函数。创ServiceTest.Binder的对象,通过这个对象来实现通信传值。
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();
}
}
}
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);
}
}
运行截图:
原文地址:https://blog.csdn.net/qq_50272406/article/details/126096684
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_21432.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!