关于 Fragment 不显示的问题

一支万宝路 2020-07-25 04:18:30
ViewActivity.java :

public class ViewActivity extends AppCompatActivity {


private MainFragment mainFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);

//实例化MainFragment
mainFragment = new MainFragment();
//将Fragment添加到container中
getSupportFragmentManager().beginTransaction().add(R.id.fl_container,mainFragment).commitAllowingStateLoss();
}
}



与它关联的xml文件, activity_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragment.ViewActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="activity_view"
android:textSize="20dp"
android:id="@+id/tv_4"
android:textColor="#000"/>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/tv_4"
android:id="@+id/fl_container" />

</RelativeLayout>


创建的 MainFragment 类

public class MainFragment extends Fragment {
private TextView tv_3;
private View view;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

view = inflater.inflate(R.layout.main_fragment,container,false);
return view;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv_3 = (TextView) view.findViewById(R.id.tv_3);
}
}


与它关联的xml文件,main_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="主页"
android:gravity="center"
android:textSize="50dp"
android:textColor="#000"
android:id="@+id/tv_3"/>

</LinearLayout>


代码的情况就是这样,但是 FrameLayout 那一部分显示不出来


有没有大佬能帮我看下怎么解决这个问题啊啊啊啊
...全文
5538 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
闫文敬 2020-07-27
  • 打赏
  • 举报
回复
你的整体逻辑没问题,beginTransaction().add(),已经添加到事务里了,但是你仅仅是添加,没有调用show()方法,改为beginTransaction().add(xxx).show(xxx)即可

80,349

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧