How Do I Create A Button Programatically? September 29, 2023 Post a Comment I just want to dynamicly add buttons to my Layout when i want to. The buttons should be like this XML Button: Solution 1: If you want to create dynamic view (like Button,textview etc) then just use this code and run it in your application.MyActivity.java://your java file LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1); Button btn = new Button(this) btn.setText("My Dynamic Button); btn.setMinLines(1); btn.setMaxLines(3); ll.addView(et); CopyIn XML File: <LinearLayout android:id="@+id/linearLayout1"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_alignBottom="@+id/TextView01"android:layout_below="@+id/relativeLayout1"android:orientation="vertical" > CopySolution 2: You can absolutely create buttons in code but it's not considered a best-practice unless you have a good reason for dynamically creating the controls. Check out this post Add an array of buttons to a GridView in an Android application.Solution 3: Try usingButtonb=newButton(); CopyThis gives you a View instance that can be added to your current parent activity or fragmnet view. For a full reference of possible settings look at http://developer.android.com/reference/android/widget/Button.htmlYou can use all the set methods provided by parent views in the object hierarchy. Solution 4: If you need to align text to the bottom of the button, all you need is:Buttonbutton= ... //apply required paramteres button.setGravity(Gravity.BOTTOM); CopySolution 5: use below code.you also add other parameters Button submit=new Button(this); LinearLayout.LayoutParams params= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(25, 0, 25, 0); submit.setLayoutParams(params); submit.setText("Attack"); submit.setTextSize(10); submit.setTextColor(getResources().getColor(R.color.white)); submit.setBackgroundResource(R.drawable.attack); Copy Share Post a Comment for "How Do I Create A Button Programatically?"
Post a Comment for "How Do I Create A Button Programatically?"