gpt4 book ai didi

android - 如何在 MainActivity 的框架布局中加载默认 fragment ?

转载 作者:行者123 更新时间:2023-11-29 15:39:40 24 4
gpt4 key购买 nike

我在 mainActivity 中有 2 个 fragment frameLayout。每当我运行我的应用程序时,我都希望将我的 Fragment1 加载到位于 mainActivity 中的 frameLayout default 中。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.prank.fragmentbackstack.MainActivity">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frame"
>

</FrameLayout>
</RelativeLayout>

fragment 类

import android.widget.Button;
import android.widget.TextView;
public class Frag extends Fragment {
String Tag1="frag1";

Button b;

public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle saveInstanceState)
{View view = inflater.inflate(R.layout.fragment, viewGroup, false);
b=(Button)view.findViewById(R.id.button);

return view;
}
}

最佳答案

使用此代码动态添加您的 fragment

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

关于android - 如何在 MainActivity 的框架布局中加载默认 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42855482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com