android:paddingRight=“@dimen/activity_horizontal_margin”
android:paddingTop=“@dimen/activity_vertical_margin”
tools:context=“scut.carson_ho.fragment_2_activity.MainActivity”>
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“等待Fragment发送消息” />
android:layout_below=“@+id/text”
android:layout_centerInParent=“true”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content” />
android:layout_below=“@+id/button”
android:id=“@+id/fragment_container”
android:layout_width=“match_parent”
android:layout_height=“500dp”/>
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
android:orientation=“vertical”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:background=“@color/colorAccent”/>
void get_message_from_Fragment(String string);
}
public class Fragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.fragment, container, false);
}
public void sendMessage(ICallBack callBack){
callBack.get_message_from_Fragment(“消息:我来自Fragment”);
}
}
public class MainActivity extends AppCompatActivity {
TextView textview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
textview = findViewById(R.id.text);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
final mFragment fragment = new mFragment();
// 即将创建的fragment 《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》无偿开源 徽信搜索公众号【编程进阶路】 添加到Activity布局文件中定义的占位符中(FrameLayout)
fragmentTransaction.add(R.id.fragment_container, fragment);
button.setOnClickListener(new View.OnClickListener() {
// 通过接口回调将消息从fragment发送到Activity
fragment.sendMessage(new ICallBack() {
@Override
public void get_message_from_Fragment(String string) {
}
});
}
});
}
原文地址:https://blog.csdn.net/m0_70083038/article/details/124567682
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_48584.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!