• Android——Activity和Fragment的通信方式


    Activity之间的通信

    1. 使用startActivityForResult启动Activity
    //在mainActivity中封装Bundle数据到Intent中再启动AACtivity
    Intent intent = new Intent(MainActivity.this,AActivity.class);
    Bundle bundle = new Bundle();
    bundle.putString("name","zhangsan");
    bundle.putInt("age",18);
    intent.putExtra("user",bundle);
    startActivityForResult(intent,0);
    //在AACtivity中获取数据并显示
    ntent intent = getIntent();
    Bundle bundle = intent.getBundleExtra("user");
    String str = "name:";
    str += bundle.getString("name");
    str += ",age:" + bundle.getInt("age");
    mTvAShow.setText(str);
    //关闭AActivity并且回传数据到MainACtivity显示
    Intent intent = getIntent();
    Bundle bundle = intent.getBundleExtra("user");
    bundle.putString("name","lisi");
    bundle.putInt("age",20);
    setResult(200,intent);
    finish();
    //重写AActivity中的关于回退的处理
    @Override
    public void onBackPressed() {
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("user");
        bundle.putString("name","lisi");
        bundle.putInt("age",20);
        setResult(200,intent);
        super.onBackPressed();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    1. 使用类的静态变量
      在MainActivity中设置静态变量,在其他Activity中可以直接使用类名.静态变量名来访问,在其他Activity中可以定义监听器接口,并在MainActivity中注册,当其他类中对MainActivity中的静态变量进行更改时可以通知到MainActivity进行操作。
    //MainActivity中
    static User user = new User();
    //MainActivity中的监听器注册
    AActivity.aActivityListener = new AActivity.AActivityListener(){
        @Override
        public void getMessage() {
            String str = "name:";
            str += user.name;
            str += ",age:" + user.age;
            mTvShow.setText(str);
        }
    };
    //AActivity中的静态监听器变量
    public static AActivityListener aActivityListener;
    //AActivity中的监听器接口定义
    public interface AActivityListener{
    	public void getMessage();
    }
    //改变数据并且回调MainACtivity中的方法
    MainActivity.user.name = "lisi";
    MainActivity.user.age = 20;
    aActivityListener.getMessage();
    finish();
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    1. 使用Application实现
    //继承Application并在自己的app类中携带数据
    public class MyApplication  extends Application { {
        //此处声明一个public static 成员来实现数据通信
        private static String name = "Son of the sea"; 
        public void setName(String name){
              this.name = name;
        }
       public String getName() {
            return this.name ;
        }
    }
    //其它Activity中获取或者改变数据的方式
    MyApplication  app = (MyApplication) getApplicationContext();
    app.setName("Son of the king"); 
    //必须在清单文件中加以说明
    <application
       android:name=".MyApplication " 
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name" >
       <activity
           android:label="@string/app_name"
           android:name=".MainActivity" >
           <intent-filter >
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
    </application>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    1. 借助外部存储完成通讯
      借助SharedPerference、File和SQLite都可以完成,这里不再赘述。

    1. 借助广播和Service实现
      由于Activity中的通信使用第一种方式已经足够使用,这两种方式虽然都可以实现,但是如没有必要,建议不要使用。

    Activity与Fragment之间的通信

    1. Activity向Fragment传递数据
    //在Fragment中提供newInstance的方法:用于Activity向Fragment中传入数据
    public static ContentFragment newInstance(String argument){          
    	Bundle bundle = new Bundle();          
    	bundle.putString("msg", argument);          
    	ContentFragment contentFragment = new ContentFragment();          
    	contentFragment.setArguments(bundle);         
    	return contentFragment;      
    }
    // 在Fragment的onCreate方法中获取Activity中传入的参数
    @Override      
    public void onCreate(Bundle savedInstanceState){          
    	super.onCreate(savedInstanceState);                 
    	Bundle bundle = getArguments();          
    	if (bundle != null)              
    	mArgument = bundle.getString("tag");        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    1. Fragment向Activity传递数据
    //Fragment中添加监听器成员并定义接口
    private onTestListener listener;
    public interface onTestListener{  
    	public void onTest(String str);  
    }
    //Fragment中提供注册监听的方式
    public setTestListener(onTestListener callback){
    	listener = callback;
    }
    //Fragment在需要向Activity中发送数据时,调用监听器方法
    listener.onTest(string);
    //Activity中设置注册监听器并提供实现
    Fragment fragment = new ContentFragment();
    fragment.setTestListener(new ContentFragment.onTestListener(){
    	@Override
        public void onTest(String str) {
        	Log.d(TAG,str);
            //执行更新UI操作或其他操作
        }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    Fragment之间的通信

    //FragmentA发消息给FragmentB
    //在FragmentA中通过以下调用获得FragmentB的引用并设置参数
    //在FragmentB中可以获得此参数
    Fragment fragment = activity.getFragmentManager().findFragmentByTag(R.id.fragmentb);
    Bundle bundle = new Bundle();
    bundle.putString("msg",string);
    fragment.setArguments(bundle);
    //FragmentB主动向FragmentA发送数据:FragmentB中定义接口
    //FragmentA调用设置监听的方法提供监听器实现
    //FragmentB在需要传送数据时调用监听器方法即可
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 获取Fragment引用的几种方式

    适合在layout中定义的单个fragment
    getSupportFragmentManager().findFragmentById();
    适合定义的多个fragment,可在xml文件和代码中添加tag
    getSupportFragmentManager().findFragmentByTag();

  • 相关阅读:
    MySQL的DCL语句
    STM32F407ZGT6|SPI主从模式
    LeetCode3. 无重复字符的最长子串
    【带头学C++】----- 六、结构体 ---- 6.6 结构体的指针成员
    van-calendar 实现移动端日历效果
    Word控件Spire.Doc 【段落处理】教程(十四):如C#/VB.NET:删除 Word 中的空行
    Ansible教程
    计算机毕业设计SSM电影推荐网站【附源码数据库】
    简述信息都有哪些特征?
    解决C语言编译undefined reference to ‘pow’问题
  • 原文地址:https://blog.csdn.net/qq_43745685/article/details/126508890