我在Android Studio中使用循环动态创建按钮。但是这些按钮彼此重叠。目前我已将循环设置为运行一定次数,最终我将使用数据库中的数字,这可能会有所不同。我试图设置这些按钮,这样无论按钮数量多少,它们总是水平居中。包括吐司,因为我无法看到是否创建了多个按钮,因为它们都在彼此之上。
LinearLayout layout = (LinearLayout)findViewById(R.id.space_layout);
for (int i = 0; i <= 3; i++ ){
Button myButton = new Button(this);// initialization of new button
myButton.setText("");
myButton.setLayoutParams(new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(myButton);
Toast.makeText(this, "Button Created" + i, Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:1)
试试这个并告诉我这是否是您正在寻找的:
MainActivity.java
package com.example.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int number = 5; // number of buttons
LinearLayout layout = (LinearLayout) findViewById(R.id.space_layout);
for (int i = 0; i < number; i++) {
Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
myButton.setText("btn " + i);
layout.addView(myButton);
}
}
}
activity_main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/space_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" />
</RelativeLayout>