简体   繁体   中英

Android adding button in FrameLayout programmatically

I was trying to make matrix using button with a certain dimension 4x4 programmatically using FrameLayout.

button = new Button[16];
for(int i = 0; i < button.length; i++)
{
    button[i] = new Button(this);
    button[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    button[i].setText("" + i);
    button[i].setOnClickListener(this);
    frameLayout.addView(button[i]);
}

Here, I have created buttons but they overlap when I run the program.

I would really appreciate if anyone would tell me how I can align buttons in frameLayout to make 4x4 matrix?

try this,

put this in your xml:

<LinearLayout
    android:id="@+id/linearlayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"/>

And put this code in you activity:

LinearLayout linearlayout = (LinearLayout) findViewById(R.id.linearlayout);

for (int i = 1; i <= 4; i++) {
        LinearLayout linearLayoutHoriztonal = new LinearLayout(this);
        linearLayoutHoriztonal.setOrientation(LinearLayout.HORIZONTAL);

        for (int j = 1; j <= 4; j++) {

            linearLayoutHoriztonal.addView(createButton("" + i));
        }
        linearlayout.addView(linearLayoutHoriztonal);
    }

Add this method to create a Buttons:

private Button createButton(String number) {
    Button button = new Button(this);
    button.setText(number);
    button.setPadding(5, 0, 5, 0);
    button.setTextSize(14f);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(WRAP_CONTENT, convertToPixel(40));
    layoutParams.setMargins(convertToPixel(10), convertToPixel(10), 0, 0);

    button.setLayoutParams(layoutParams);

    return button;
}

private int convertToPixel(int n) {
    Resources r = getResources();
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, n, r.getDisplayMetrics());
    return (int) px;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM