[英]How to create buttons dynamically in Android?
这里的xml是这样的
<com.example.MyViewGroup
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/screen"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</com.example.MyViewGroup>
MyViewGroup
类扩展了ViewGroup
。 所以我的问题是可以通过编程方式创建按钮并将其添加到视图中吗?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = new ContextThemeWrapper(getActivity(), R.style.Beam_Light);
LayoutInflater localInflater = inflater.cloneInContext(context);
final View root = localInflater.inflate(R.layout.sv_contact_info_fragment, container, false);
LinearLayout dynamicLayout = (LinearLayout) root.findViewById(R.id.beam_contact_info_fragment_lchild);
View view = localInflater.inflate(R.layout.sv_header, null);
dynamicLayout.addView(view);
}
是的,有可能。 您可以使用addView()方法
这是简单的示例:
MyViewGroup mvg = (MyViewGroup) findViewById(R.id.screen);
Button btn = new Button(context);
btn.setText("My Button");
mvg.addView(btn);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.