我有一个具有自己布局的片段,并且应该添加片段的活动具有以下布局:
<?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:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin">
<fragment
android:name="com.myapp.MyFragment"
android:id="@+id/myfragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
tools:layout="@layout/myfragment_layout" />
</RelativeLayout>
然后在活动类中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
FragmentManager fm = getFragmentManager();
fragment = fm.findFragmentById(R.id.myfragment);
if (fragment == null) {
fragment = new MyFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.myfragment, fragment, "myfragment");
ft.commit();
}
}
片段的onCreateView是:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.myfragment, container, false);
}
但片段没有显示。没有异常被抛出。活动仍然是空白。
我错过了什么?
答案 0 :(得分:4)
替换以下行
机器人:layout_weight =&#34; 1&#34; 机器人:layout_width =&#34; 0dp&#34;
带
android:layout_width="match_parent"
或 android:layout_width="wrap_content"
因为RelativeLayout
不接受layout_weight。