簡體   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