布局中动态添加View

  • 布局中动态添加View

在项目中经常会出现自定义的View,并且添加到指定布局中,中间出现过不少问题,现在我给大家详细说下,希望可以帮助大家

废话多说了,直接看代码

布局文件;activity_main.xml

<LinearLayout
        android:id="@+id/viewObj"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#cccccc"
        android:orientation="vertical" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/textContent"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="输入要发送的内容" />

        <Button
            android:id="@+id/sendContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="发送" />
    </LinearLayout>

下面是java代码:MainActivity.java

        viewObj = (LinearLayout) findViewById(R.id.viewObj);
        textContent = (EditText) findViewById(R.id.textContent);
        sendContent = (Button) findViewById(R.id.sendContent);

        sendContent.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String content = textContent.getText().toString().trim();
                if (content.length() <= 0) {
                    Toast.makeText(MainActivity.this, "请输入要发送的内容",
                            Toast.LENGTH_LONG).show();
                    return;
                } else {
                    viewObj.addView(getContent(content));
                    textContent.setText("");
                }
            }
        });

java代码中需要一个自定义的方法来显示添加的内容 如下:

public TextView getContent(String text) {
        TextView textView = new TextView(MainActivity.this);
        textView.setText(text);
        textView.setTextSize(20);
        textView.setTextColor(Color.RED);
        textView.setGravity(Gravity.CENTER);
        textView.setSingleLine(true);
        return textView;
    }

好了,代码到这里就完成了,一个简单的demo,希望可以帮到大家,下面是截图效果

效果展示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值