Java – dynamically add a button to LinearLayout in Android
•
Android
I'm developing a project that needs to add buttons dynamically. But whenever I run my application, the application closes forcibly. I already know 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);
}
}
resolvent:
Try this:
linearLayout.addView(
btn,
new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT)
);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码