【发布时间】:2016-02-10 08:30:13
【问题描述】:
我在片段中有一个布局,每次都动态创建按钮。我必须创建的按钮数量是特定数组的长度。所以我无法创建静态 XML 布局,但我创建了一个只有 1 个可见性消失的按钮的 XML 布局,我想通过 findviewbyID 使用它的布局并更改它的可见性。
我无法使用按 id 查找视图将我的按钮与 XML 按钮的 id 链接起来。我该怎么做?
部分代码。
for (int y = 0; (y < 3) && (i <= items.length); y++) {
final Button item_button = new Button(getActivity());
item_button.getRootView().findViewById(R.id.item_button_layout);
item_button.setVisibility(View.VISIBLE);
TableRow.LayoutParams par = new TableRow.LayoutParams(y);
item_button.setLayoutParams(par);
int id = i;
item_button.setId(id);
item_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int btn_selected = item_button.getId();
Fragment fragment = new ItemPageFragment();
if (fragment != null) {
FragmentManager fragmentManager = myContext.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
}
}
});
a.addView(item_button);
i++;
}
layout.addView(a);
XML 布局
<TableLayout
android:id="@+id/item_fragment_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:stretchColumns="*"
android:gravity="center_vertical" />
<Button
android:id="@+id/item_layout"
android:layout_width="300dp"
android:layout_height="0dp"
android:layout_marginTop="30dp"
android:layout_weight="40"
android:drawableLeft="@drawable/folder"
android:paddingLeft="40dp"
android:background="@drawable/item_button"
android:drawablePadding="-25dp"
android:visibility="gone"/>
</LinearLayout>
【问题讨论】:
标签: android xml button layout fragment