Dynamically adding a button to LinearLayout on Android

I am working on a project that is supposed to dynamically add buttons. But whenever I launch my application, the power of the application closes. I found out that the problem is that I am trying 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); } } 
+4
source share
3 answers

try like this:

 linearLayout.addView( btn, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) ); 
+2
source

an error will only occur if linearLayout is NULL, make sure layout1 is a valid R.layout.main element

+1
source

Try the following steps in your custom action class:

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

Source: https://habr.com/ru/post/1347679/


All Articles