Android Java集成:Activity与Fragment通信实例

原创 左手的ㄟ右手 2024-10-25 13:24 123阅读 0赞

在Android开发中,Activity和Fragment是两种常用的用户界面组件。它们之间可以通过各种方式进行通信。以下是一个简单的例子:

  1. Activity引入Fragment
    在一个Activity的布局文件中(例如res/layout/main.xml)添加一个包含Fragment的FrameLayout。
  1. <FrameLayout
  2. android:id="@+id/fragment_container"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <!-- 你的Fragment代码将放在这里 -->
  6. </FrameLayout>
  1. Fragment暴露接口
    在Fragment中,你需要创建一个接口来暴露你想要在Activity中调用的方法。
  1. // Fragment.java
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. @Retention(RetentionPolicy.RUNTIME))
  5. public interface ExampleInterface {
  6. void onMethodCalled(String message);
  7. }
  8. // fragment.xml (activity布局里)
  9. <fragment
  10. android:id="@+id/fragment"
  11. android:name="com.example.fragment.FragmentWithExampleInterface"
  12. android:layout_width="0dp"
  13. android:layout_height="match_parent"
  14. tools:layout="@layout/fragment_with_example_interface" />
  1. Activity通过接口调用Fragment方法
    在你的Activity(例如MainActivity.java)中,创建一个对象来访问你的Fragment,并通过接口调用它的方法。
  1. // MainActivity.java
  2. import android.os.Bundle;
  3. import android.view.View;
  4. import android.widget.Button;
  5. import com.example.activity.MainActivity;
  6. import com.example.fragment.FragmentWithExampleInterface;
  7. import com.example.interfacemanager.ExampleManager;
  8. public class MainActivity extends AppCompatActivity {
  9. private FragmentWithExampleInterface fragment;
  10. private ExampleManager exampleManager;
  11. @Override
  12. protected void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.activity_main));
  15. // 初始化Fragment和ExampleManager
  16. fragment = (FragmentWithExampleInterface) getSupportFragmentManager().findFragmentById(R.id.fragment_container));
  17. exampleManager = new ExampleManager(fragment);
  18. // 设置按钮事件
  19. Button button1 = findViewById(R.id.button1));
  20. button1.setOnClickListener(view -> {
  21. String messageToDisplay = "Button 1 clicked!";
  22. exampleManager.onMethodCalled(messageToDisplay);
  23. }));
  24. }
  25. }

现在,当你在MainActivity中点击按钮1时,Fragment会通过ExampleInterface接收到一个消息,并在Activity上显示出来。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,123人围观)

还没有评论,来说两句吧...

相关阅读