繁体   English   中英

在Android中动态添加Button到LinearLayout

[英]Add a Button dynamically to a LinearLayout in Android

我正在开发一个需要动态添加按钮的项目。 但每当我运行我的应用程序时,应用程序强制关闭 我已经知道问题是当我尝试添加按钮时。

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); 


    }
}

试试这样:

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

如果linearLayout为null,则只会发生错误,请确保layout1是R.layout.main的有效项

在自定义活动类中尝试以下操作:

this.addContentView(call,
    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM