Fragment

时间:2015-11-09 16:17:18

标签: android xml button layout fragment

我在片段中有一个布局,每次都会动态创建按钮。我必须创建的按钮数是特定数组的长度。所以我不能创建一个静态XML布局,但我创建了一个只有1个按钮的XML layou,可见性消失了,我想通过findviewbyID使用它的布局并更改其可见性。

我不能使用id的find view来链接我的按钮和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>

2 个答案:

答案 0 :(得分:0)

你不需要&#34;去了&#34;完全按照布局中的按钮。

1)将按钮放在单独的布局中。

2)调用Activity#getLayoutInflater()以获取LayoutInflater并以编程方式对您指定的布局ID进行膨胀,并将视图转换为Button。

button_layout.xml

<Button
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_marginTop="30dp"
     android:drawableLeft="@drawable/folder"
     android:paddingLeft="40dp"            
     android:background="@drawable/item_button"
     android:drawablePadding="-25dp"/>

然后在你的循环中:

Button button = (Button) getLayoutInflater().inflate(R.layout.button_layout, null, false);
... set your click listener
tableLayout.addView(button);

答案 1 :(得分:0)

如果有人感兴趣,解决方案是:

按钮BUTTON_NAME =(按钮)LayoutInflater.from(getActivity())。inflate(R.layout.BUTTON_NAME_layout,null,false);

相关问题