如何在 android 中以编程方式添加按钮
how to add buttons programmatically in android
我想要在我的 activity 布局中使用这样的东西:
如果用户单击“+添加其他”,那么它应该以编程方式添加一个按钮。我使用了相对布局,但它不起作用。
这是我试过的代码:
View root;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
root = inflater.inflate(R.layout.fragment_pay_remind_fragment, container, false);
Button b = new Button(getContext());
Button b1 = new Button(getContext());
Button b2 = new Button(getContext());
Button b3 = new Button(getContext());
Button b4 = new Button(getContext());
RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);;
b.setLayoutParams(rl);
RelativeLayout layout = (RelativeLayout) root.findViewById(R.id.relativeLayout);
layout.addView(b);
layout.addView(b1);
layout.addView(b2);
layout.addView(b3);
layout.addView(b4);
return root;
}
结果是这样的,我不想要
对于您的情况,我建议您使用 constraintLayout
中的 Flow
而不是 RelativeLayout
。您可以通过阅读本文了解更多信息 article.
我想要在我的 activity 布局中使用这样的东西:
如果用户单击“+添加其他”,那么它应该以编程方式添加一个按钮。我使用了相对布局,但它不起作用。
这是我试过的代码:
View root;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
root = inflater.inflate(R.layout.fragment_pay_remind_fragment, container, false);
Button b = new Button(getContext());
Button b1 = new Button(getContext());
Button b2 = new Button(getContext());
Button b3 = new Button(getContext());
Button b4 = new Button(getContext());
RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);;
b.setLayoutParams(rl);
RelativeLayout layout = (RelativeLayout) root.findViewById(R.id.relativeLayout);
layout.addView(b);
layout.addView(b1);
layout.addView(b2);
layout.addView(b3);
layout.addView(b4);
return root;
}
结果是这样的,我不想要
对于您的情况,我建议您使用 constraintLayout
中的 Flow
而不是 RelativeLayout
。您可以通过阅读本文了解更多信息 article.