Android的 - 添加按钮到现有的编程布局 [英] Android - Adding Buttons into an existing layout programatically

查看:227
本文介绍了Android的 - 添加按钮到现有的编程布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个音板的应用程序,在这里我有一些predefined按钮在tablelayout,这是嵌套在一个相对布局中。布局是自己的片段(我用不同类别的多个选项卡)。

I am building a soundboard app, where I have some predefined buttons in a tablelayout, which is nested inside a relative layout. The layout is an own fragment (I use multiple tabs for different categories).

声音和标签工作正常,现在我要实现的功能,您生成一个新的按钮,一旦你点击+按钮,并在+按钮移动新按钮下方一行。

Sound and tabs are working fine, now I want to implement the function, that you generate a new button, once you click the "+" button and that the "+" button moves one row beneath the new button.

有没有一种方法来生成一个新tablelayout,具有相同的属性已经存在,而无需使用XML的文件中的空白?

Is there a way to generate a new tablelayout, with the same attributes as the already existing without having to use blanks inside the xml-file?

推荐答案

试试这个简单的例子,并修改为按您的要求。

try this simple example and modify as per your requirement

 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的 - 添加按钮到现有的编程布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆