在Android上以编程方式创建按钮

时间:2014-08-22 09:42:01

标签: android button margin

我想在每个Button之间动态创建带有Margin的10个按钮,但我尝试过的东西不起作用。

以下是我正在使用的代码:

//Create Button
for(int i = 1; i <= 10; i++){
    MarginLayoutParams params = new MarginLayoutParams(MarginLayoutParams.MATCH_PARENT, MarginLayoutParams.MATCH_PARENT);
    params.setMargins(10, 0, 10, 0); 
    params.leftMargin = xpos;
    params.topMargin = ypos;
    params.width = 250;
    params.height = 150;    

    Button btn = new Button(this);
    btn.setId(i);
    final int _id = btn.getId();
    btn.setLayoutParams(params);
    btn.setText("Button " + _id);
    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Toast.makeText(v.getContext(), "Button clicked index =" + _id, Toast.LENGTH_LONG).show();

            //Intent einauslagern = new Intent(v.getContext(), JockeyEinauslagern.class);
            //startActivityForResult(einauslagern, 0);
        }
    });
    xpos += 20;
    ypos += 50;
    this.addContentView(btn, params);
}

2 个答案:

答案 0 :(得分:0)

您可能希望在此类Activity类中获取容器。 (例如,让它为LinearLayout

您的XML -

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container"
    android:orienation="vertical"
/>

你的Java -

LinearLayout container = (LinearLayout) findViewById(R.id.container);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
//set your margins here
for (int i = 0; i < 10; i++) {
    Button button = new Button(this);
    // some stuff
    container.addView(button, llp);
}

通过微小的修改,这应该可以正常工作。

答案 1 :(得分:0)

试试这个

for (int i = 0; i < count; i++) {

// creates button
final Button btn = new Button(this);
btn.setLayoutParams(new ViewGroup.LayoutParams(
250,150));
btn.setPadding(0, 8, 0, 8); //or set margin if u need
btn.setTag(i);

yourContainserView.addView(channelBtn, i);
}