我正在尝试将checkbox
添加到fragment
,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/addProductButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="Add Product" />
</LinearLayout>
然后我创建checkBox
并尝试将其添加到fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_product_list, container, false);
LinearLayout ll = new LinearLayout(getActivity());
ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < 20; i++) {
CheckBox cb = new CheckBox(rootView.getContext());
ll.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
cb.setText("check");
ll.addView(cb);
}
return rootView;
}
}
但是复选框不可见。
答案 0 :(得分:0)
你不能添加相同的CheckBox实例20次。您需要在每次迭代时创建一个新的。移动
在for循环中
for (int i = 0; i < 20; i++) {
CheckBox cb = new CheckBox(rootView.getContext());
ll.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
cb.setText("check");
ll.addView(cb);
}
答案 1 :(得分:0)
为你的linearLayout添加一个id,如:
android:id="@+id/linearLayout"
然后在你的代码中你有:
LinearLayout ll = rootView.findViewById(R.id.linearLayout);
// other code
另一种必须工作的方法是创建一个布局并添加视图,并将此linearLayout
添加到该
答案 2 :(得分:0)
更改此类onCreateView()
方法..不需要findViewById()
或其他任何
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout rootView = (LinearLayout) inflater.inflate(
R.layout.fragment_product_list, container, false);
// LinearLayout ll = new LinearLayout(getActivity());
rootView.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < 20; i++) {
CheckBox cb = new CheckBox(rootView.getContext());
rootView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
cb.setText("check");
rootView.addView(cb);
}
return rootView;
}