我正在尝试做一些应该简单的事情,我的主要布局是这样的
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:name="io.raindance.kalimat.grid.GridFragment"
android:id="@+id/gridControlInMainView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
主要活动中没有Java代码;现在GridFragment的代码和布局就像这样:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridFragmentMainContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
</LinearLayout>
Java代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Load the layout of the rack tile
View view = inflater.inflate(R.layout.grid_fragment, null, false);
// Get the root linear layout to add the rows to it
LinearLayout root = (LinearLayout) view.findViewById(R.id.gridFragmentMainContainer);
// Build the rows of the grid
int rowsId = 21;
for (int i = 0; i < 15; i++) {
// Create the linear layout that represents a row in the grid
LinearLayout row = new LinearLayout(this.getActivity());
row.setId(rowsId++);
row.setOrientation(LinearLayout.HORIZONTAL);
row.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 10, 1.0f));
// Build the cells of the grid
for (int j = 0; j < 15; j++) {
// Create the cell fragment
CellFragment cellFragment = new CellFragment();
// Add the cell fragment to the row fragment
this.getFragmentManager().beginTransaction().add(row.getId(), cellFragment).commit();
}
// Add the row to the root element
root.addView(row);
}
return view;
}
CellFragment布局简单如下所述,并且没有Java代码。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lll1"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent">
</LinearLayout>
当我运行应用程序时,由于commit()调用,我得到一个异常,导致在我删除commit()调用时没有引发异常,并且无论如何成功创建了行并将其添加到层次结构中。< / p>
我得到以下异常 07-08 03:36:27.414:E / AndroidRuntime(835):java.lang.RuntimeException:无法启动活动ComponentInfo {io.raindance.kalimat / io.raindance.kalimat.test.KalimatActivity}:java.lang.IllegalArgumentException :没有为片段CellFragment找到id 0x7f050005的视图{4103c790#1 id = 0x7f050005}
我一直在寻找这个问题的原因和解决方案2天。
答案 0 :(得分:0)
需要创建Activity
(并保存其状态)以便执行FragmentTransaction
,否则您将获得异常。请尝试在onActivityCreated
中执行您的交易。