Android 片段中的按钮自定义视图
我在一个片段中有一个布局,每次按钮都是动态创建的。我必须创建的按钮数是特定数组的长度。因此,我无法创建静态XML布局,但我创建了一个XML布局,其中只有一个按钮的可见性消失,我希望通过findviewbyID使用其布局并更改其可见性 我无法使用“按id查找视图”将我的按钮与XML按钮的id链接。我怎么做 代码的一部分Android 片段中的按钮自定义视图,android,xml,button,layout,fragment,Android,Xml,Button,Layout,Fragment,我在一个片段中有一个布局,每次按钮都是动态创建的。我必须创建的按钮数是特定数组的长度。因此,我无法创建静态XML布局,但我创建了一个XML布局,其中只有一个按钮的可见性消失,我希望通过findviewbyID使用其布局并更改其可见性 我无法使用“按id查找视图”将我的按钮与XML按钮的id链接。我怎么做 代码的一部分 for (int y = 0; (y < 3) && (i <= items.length); y++) { final
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);
对于(int y=0;(y<3)和&(i布局中根本不需要“gone”按钮
1) 将按钮放在单独的布局中
2) 调用活动#GetLayoutFlater()以获取LayoutFlater并以编程方式膨胀指定的布局id,并将视图强制转换为按钮
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\u NAME=(Button)LayoutFlater.from(getActivity()).inflate(R.layout.Button\u NAME\u layout,null,false) 你能给我解释一下吗?好的,我试过了,但是GetLayoutFlater()中有一条红线。“In fragment无法应用于()”请确保使用:android.support.v4.app.fragment包
<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);