以编程方式创建多个按钮:Android [英] Creating multiple buttons programmatically: Android
问题描述
我知道这已经被问过几次了,但是我无法解决我的问题.我正在尝试以编程方式添加多个按钮.我希望按钮水平对齐.但是,仅显示一个按钮.到目前为止,我尝试过的是
I know that this has been asked several times before but I can't get a solution to mine issue. I am trying to add multiple buttons programmatically. I want the buttons to be aligned horizontally. However, only one button is showing up. What I have tried so far is,
private void locationSort() {
RelativeLayout townLayout = (RelativeLayout) locationLayout.findViewById(R.id.town_sort);
for (int i = 0; i <= 3; i++) {
LayoutInflater inflater = getLayoutInflater();
Button btnTag = (Button) inflater.inflate(R.layout.buttons, null,
false);
for (int j = 0; j < 4; j++) {
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button");
btnTag.setBackgroundResource(R.drawable.alpha_button_selector);
btnTag.setClickable(true);
btnTag.setTextColor(Color.WHITE);
btnTag.setGravity(Gravity.CENTER);
btnTag.setId(j);
}
townLayout.addView(btnTag);
btnTag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "this is test", Toast.LENGTH_SHORT).show();
}
});
}
}
我搜索了相同的内容,并通过了
I have searched on the same and gone through the links like,
- Android: programmatically adding buttons to a layout
- Android - How to add several buttons with different layout_margins in a LinearLayout programmatically?
- android add multiple buttons on fly
以及许多其他功能,但是我不能在此处创建多个按钮.每次仅显示一个按钮. 谁能帮忙吗?
and many other, but I can't make multiple buttons here. Only a single button is being displayed everytime. Can anyone please help?
推荐答案
首先,您应该使用LinearLayout
而不是RelativeLayout
来使用HORIZONTAL
方向,因为在Relative
中,所有视图都将位于同一地方(这就是为什么您只能看到一个Button
的原因)
First of all, you should use LinearLayout
with HORIZONTAL
orientation, istead of RelativeLayout
, because in Relative
all your views will be in the same place (that's why you can see only one Button
)
这篇关于以编程方式创建多个按钮:Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!