Android - 以编程方式将按钮添加到现有布局中

标签 android layout tablelayout

我正在构建一个音板应用程序,其中我在表格布局中有一些预定义的按钮,这些按钮嵌套在相关布局中。布局是一个自己的 fragment (我为不同的类别使用多个选项卡)。

(I will post an image here as soon as I have the 10 reps)

声音和选项卡工作正常,现在我想实现这个功能,即在您单击“+”按钮后生成一个新按钮,并且“+”按钮在新按钮下方移动一行。

有没有办法生成一个新的表格布局,具有与现有表格相同的属性,而不必在 xml 文件中使用空白?

最佳答案

尝试这个简单的例子并根据您的要求进行修改

 public class MainActivity extends Activity {
        Context context;
        ScrollView scrollView;
        LinearLayout container;
        LinearLayout layout;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            context = this;
            setContentView(R.layout.activity_main);
             layout = (LinearLayout) findViewById(R.id.LinearAdd);


        }

        public void addButton(View view) {
            Button button  = new Button(MainActivity.this);
            LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT );
            button.setLayoutParams(lp);
            button.setText("ADDED");
            layout.addView(button);
        }

    }

And this your xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/LinearAdd"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="70"
        android:orientation="vertical" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="addButton"
            android:text="click to add" />
    </LinearLayout>

</LinearLayout>

关于Android - 以编程方式将按钮添加到现有布局中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22067180/

相关文章:

android - Glide 4 - ModelLoader 上下文

java - Android Studio 3.0 布局编辑器/预览器

android - 在 TableLayout 中对齐列

android - 在 Windows 上手动安装 Android SDK 4.1 时,我应该在哪里提取 armeabi-v7a 存档?

android - Google Maps Android API v2 - 恢复 map 状态

Android 使用 viewPager 与使用 tabhost

CSS Flex 网格 - 最后一项的宽度相同

iPhone——UIViews 的布局管理器?

android XML TableLayout 问题 : horizontal scroller going outside of right side of screen

c# - 如何使用 TableLayout 创建我想要的设计?