动态地添加一个按钮,在Android上的LinearLayout [英] Add a Button dynamically to a LinearLayout in Android

查看:171
本文介绍了动态地添加一个按钮,在Android上的LinearLayout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作,需要动态地添加按钮的项目。但每当我运行我的应用程序的应用力关闭。我已经学会了,问题是,当我尝试添加的按钮。

 包com.Feras.TestProject;
进口android.app.Activity;
进口android.os.Bundle;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.view.ViewGroup.LayoutParams;
进口android.widget.Button;
进口android.widget.LinearLayout;公共类TestProject延伸活动{
    / **当第一次创建活动调用。 * /
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);    的setContentView(R.layout.main);
    的addAll();
    //在旧约按钮设置文本}
公共无效的addAll(){
    LinearLayout中的LinearLayout =(的LinearLayout)findViewById(R.id.layout1);
    按钮BTN =新按钮(本);
    btn.setText(用作MyButton);
    linearLayout.addView(BTN);
    }
}


解决方案

尝试这样的:

  linearLayout.addView(
                     BTN,
                     新的LayoutParams(
                          LayoutParams.WRAP_CONTENT,
                          LayoutParams.WRAP_CONTENT)
                     );

I am working on a project that needs to add buttons dynamically. But whenever i run my application the application force closes. I've learned that the problem is when i try to add buttons.

package com.Feras.TestProject;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class TestProject extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    AddAll();
    // Set Text for the button in the Old Testament



}
public void AddAll() {
    LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout1);
    Button btn = new Button(this); 
    btn.setText("MyButton"); 
    linearLayout.addView(btn); 


    }
}

解决方案

try like this:

linearLayout.addView(
                     btn, 
                     new LayoutParams(
                          LayoutParams.WRAP_CONTENT, 
                          LayoutParams.WRAP_CONTENT)
                     );

这篇关于动态地添加一个按钮,在Android上的LinearLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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