问题
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