Android Java集成:Activity与Fragment通信实例
在Android开发中,Activity和Fragment是两种常用的用户界面组件。它们之间可以通过各种方式进行通信。以下是一个简单的例子:
- Activity引入Fragment:
在一个Activity的布局文件中(例如res/layout/main.xml)添加一个包含Fragment的FrameLayout。
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 你的Fragment代码将放在这里 -->
</FrameLayout>
- Fragment暴露接口:
在Fragment中,你需要创建一个接口来暴露你想要在Activity中调用的方法。
// Fragment.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME))
public interface ExampleInterface {
void onMethodCalled(String message);
}
// fragment.xml (activity布局里)
<fragment
android:id="@+id/fragment"
android:name="com.example.fragment.FragmentWithExampleInterface"
android:layout_width="0dp"
android:layout_height="match_parent"
tools:layout="@layout/fragment_with_example_interface" />
- Activity通过接口调用Fragment方法:
在你的Activity(例如MainActivity.java)中,创建一个对象来访问你的Fragment,并通过接口调用它的方法。
// MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.activity.MainActivity;
import com.example.fragment.FragmentWithExampleInterface;
import com.example.interfacemanager.ExampleManager;
public class MainActivity extends AppCompatActivity {
private FragmentWithExampleInterface fragment;
private ExampleManager exampleManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main));
// 初始化Fragment和ExampleManager
fragment = (FragmentWithExampleInterface) getSupportFragmentManager().findFragmentById(R.id.fragment_container));
exampleManager = new ExampleManager(fragment);
// 设置按钮事件
Button button1 = findViewById(R.id.button1));
button1.setOnClickListener(view -> {
String messageToDisplay = "Button 1 clicked!";
exampleManager.onMethodCalled(messageToDisplay);
}));
}
}
现在,当你在MainActivity中点击按钮1时,Fragment会通过ExampleInterface接收到一个消息,并在Activity上显示出来。
还没有评论,来说两句吧...