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 那一部分顯示不出來

有沒有大佬能幫我看下怎么解決這個問題啊啊啊啊
uj5u.com熱心網友回復:
你的整體邏輯沒問題,beginTransaction().add(),已經添加到事務里了,但是你僅僅是添加,沒有呼叫show()方法,改為beginTransaction().add(xxx).show(xxx)即可轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/18850.html
標籤:Android
下一篇:android圖片問題請教
