簡體   English   中英

Android:如何以編程方式將按鈕添加到布局(在 XML 視圖中可以看到按鈕)

[英]Android: How to add Buttons to a Layout programmatically(with Buttons to be seen in the XML-View)

正如標題所述,我確實想以編程方式將按鈕添加到 ConstraintLayout,這意味着在 XML 文件中可以看到添加的按鈕。

XML 文件:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:id="@+id/idMain">

</androidx.constraintlayout.widget.ConstraintLayout>

添加按鈕的代碼:

ConstraintLayout cst = (ConstraintLayout) findViewById(R.id.idMain);
Button btn = new Button(this);
btn.setText("Hallo Welt");
cst.addView(btn);

問題:在 XML 文件中看不到添加的按鈕。 問題:如何將 append 的按鈕轉換為 XML 文件?

向上

使用此代碼 XML

    <android.support.constraint.ConstraintLayout
         android:id="@+id/ly_id"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginBottom="10dp"
         android:layout_marginLeft="10dp"
         android:layout_marginRight="10dp"
         android:layout_marginTop="0dp">

    </android.support.constraint.ConstraintLayout>

Java 代碼以編程方式添加按鈕。

    ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.ly_id);

    //set the properties for button
    Button btnTag = new Button(this);
    btnTag.setText("Button");
    btnTag.setId(some_random_id);

    //add button to the layout
    layout.addView(btnTag);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM