Add a Button dynamically to a LinearLayout in Android

此生再无相见时 提交于 2019-12-10 16:59:10

问题


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


    }
}

回答1:


try like this:

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



回答2:


there will only occure an error if linearLayout is null, ensure that layout1 is a valid Item of R.layout.main




回答3:


Try the following in your custom activity class:

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


来源:https://stackoverflow.com/questions/5631913/add-a-button-dynamically-to-a-linearlayout-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!