【问题标题】:Android: How to add Buttons to a Layout programmatically(with Buttons to be seen in the XML-View)Android:如何以编程方式将按钮添加到布局(在 XML 视图中可以看到按钮)
【发布时间】:2020-10-22 22:36:35
【问题描述】:

正如标题所述,我确实想以编程方式将按钮添加到 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 文件中无处可见。 问题:如何将按钮附加到 XML 文件?

向上

【问题讨论】:

    标签: android xml android-studio button


    【解决方案1】:

    使用此代码 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);
    

    【讨论】:

      猜你喜欢
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 2011-11-03
      • 2013-07-17
      • 2014-04-26
      相关资源
      最近更新 更多