Android create button programmatically

Create a new Button Programmatically in Kotlin Android

Create EditText Programmatically

We know that we can specify Button widget using layout file. But, we can also create a Button programmatically and then add this to a specific View as child, in layout file.

In this tutorial, we will learn how to create a Button widget programmatically in Android, and add this Button to a LinearLayout in layout file.

Code – Create EditText in Kotlin File

A quick snippet of code to create a new Button programmatically in Kotlin Android

Creating a new Button programmatically at a point in the program requires it to be in UI thread. And also we need the application context to create any new View. Android prevents any View to be created outside the UI thread by throwing a build error.

In this Android Tutorial, we shall learn how to create a Button programmatically and add the Button to a LinearLayout using Kotlin.

activity_main.xml: Following is the activity_main.xml containing an empty LinearLayout to which we shall add the dynamic Button.

MainActivity.kt: We shall create a new Button with text “Dynamic Button” and add it to the LinearLayout. This addition makes the dynamically created Button to be appended at the end of all child views present in the LinearLayout.

Following is the Output with layout bounds :

Conclusion

In this Kotlin Android Tutorial, we have learned to create Button programmatically and add it to layout.

Источник

Buttons

A button consists of text or an icon (or both text and an icon) that communicates what action occurs when the user touches it.

Depending on whether you want a button with text, an icon, or both, you can create the button in your layout in three ways:

  • With text, using the Button class:
  • With an icon, using the ImageButton class:
  • With text and an icon, using the Button class with the android:drawableLeft attribute:

Key classes are the following:

Responding to Click Events

When the user clicks a button, the Button object receives an on-click event.

To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

For example, here’s a layout with a button using android:onClick :

Within the Activity that hosts this layout, the following method handles the click event:

Kotlin

The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:

  • Be public
  • Return void
  • Define a View as its only parameter (this will be the View that was clicked)

Using an OnClickListener

You can also declare the click event handler programmatically rather than in an XML layout. This might be necessary if you instantiate the Button at runtime or you need to declare the click behavior in a Fragment subclass.

To declare the event handler programmatically, create an View.OnClickListener object and assign it to the button by calling setOnClickListener(View.OnClickListener) . For example:

Kotlin

Styling Your Button

The appearance of your button (background image and font) may vary from one device to another, because devices by different manufacturers often have different default styles for input controls.

You can control exactly how your controls are styled using a theme that you apply to your entire application. For instance, to ensure that all devices running Android 4.0 and higher use the Holo theme in your app, declare android:theme=»@android:style/Theme.Holo» in your manifest’s element. Also read the blog post, Holo Everywhere for information about using the Holo theme while supporting older devices.

To customize individual buttons with a different background, specify the android:background attribute with a drawable or color resource. Alternatively, you can apply a style for the button, which works in a manner similar to HTML styles to define multiple style properties such as the background, font, size, and others. For more information about applying styles, see Styles and Themes.

Читайте также:  Как взломать fifa 14 для андроид

Borderless button

One design that can be useful is a «borderless» button. Borderless buttons resemble basic buttons except that they have no borders or background but still change appearance during different states, such as when clicked.

To create a borderless button, apply the borderlessButtonStyle style to the button. For example:

Custom background

If you want to truly redefine the appearance of your button, you can specify a custom background. Instead of supplying a simple bitmap or color, however, your background should be a state list resource that changes appearance depending on the button’s current state.

You can define the state list in an XML file that defines three different images or colors to use for the different button states.

To create a state list drawable for your button background:

    Create three bitmaps for the button background that represent the default, pressed, and focused button states.

To ensure that your images fit buttons of various sizes, create the bitmaps as Nine-patch bitmaps.

Источник

Tutorialwing

Hello Reader! In this post, we are going to learn about creating android button programmatically in android. We will go through different steps that explains how to create and use android button programmatically in any android application.

Output

Android Dynamic Button Output

Android Dynamic Button Output

Video Output

1. Creating New Project

At First, we will create android application in android. Then, we will use button dynamically. Please ignore the steps if you have already created the project.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as DynamicButton. Then, click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. If you have followed above process correctly, you will get a newly created project successfully. However, you can also visit post to create a new project to know steps in detail.

Now, we will modify java and xml file to use button programmatically.

2. Modify Values Folder

Open res/values/strings.xml file and add below code into it.

Other values folder have not been changed. So, we are not going to mention it here.

3. Modify Layout Folder

Open res/layout/activity_main.xml file and add below code into it.

Here, We have only LinearLayout that acts as container for the Button created in java file at run time. Now, we will add code to create Button programmatically in java file.

4. Create Android Button Programmatically / Dynamically

Open app/src/main/java/com.tutorialwing.dynamicebutton/MainActivity.java file and add below code into it. You may also visit post to use Button widget in xml file in android

In MainActivity.java file, we have created button programmatically. Then, we have added it in LinearLayout having id rootContainer.
Due to Importance of Manifest file in any project, we are also going to see the code inside this file.

AndroidManifest.xml file

Code inside src/main/AndroidManifest.xml file would look like below –

Now, run the application. We will get the output as shown above.

That’s end of Tutorial on Creating Android Button programmatically in java project.

Источник

Tutorialwing

Hello Readers! In this post, we are going to learn how to create and use android imageButton programmatically in any android application. We will also learn to add imageButton in linearLayout programmatically in any application.

Output

Tutorialwing Android Dynamic ImageButton Output

Tutorialwing Android Dynamic ImageButton Output

Getting Started

At first, we will create an android application. Then, we will use imageButton widget in the application.

1. Creating New Project

Follow the steps below to create a new project. Please ignore the steps if you have already created a new project.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as DynamicImageButton. Then, click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. If you have followed above process correctly, you will get a newly created project successfully. However, you can also visit post to create a new project to know steps in detail.

Now, we will modify xml and java file to use android imageButton programmatically.

2. Modify values folder

Open res/values/strings.xml file and add below code into it.

No other values folders have been modified. So, we are not going to mention them here.

3. Modify Layout Folder

Open res/layout/activity_main.xml file. Then, add below code into it.

Читайте также:  Speedtest для андроид 4pda

In activity_main.xml file, we have defined a linearLayout, with id rootContainer, that will act as container for the imageButton widget created dynamically in the application.

4. Create Android ImageButton Programmatically / Dynamically

Open app/src/main/java/com.tutorialwing.dynamicimagebutton/MainActivity.java file and add below code into it.

In MainActivity.java file, we have create imageButton programmatically. Then, we have set layout params and image in it. After that, we have set a listener clickListener to show a toast message when it is clicked. At last, we have added this newly created imageButton in linearLayout, having id rootContainer. Similarly, you can add imageButton in relativeLayout or frameLayout etc.

Since AndroidManifest.xml file is very important in any android project. We are also going to see the content inside this file.

AndroidManifest.xml file

Code inside src/main/AndroidManifest.xml file would look like below –

When we run the application, we will get output as shown above.

That’s the end of tutorial on Creating Android imageButton Programmatically.

Источник

Tutorialwing

In this article, we will learn how to create android Toggle Button programmatically in Kotlin. We will go through various steps that explains how to create Toggle Button and add it in kotlin file, use different attributes to customise it etc. in any android application. For example, how to set text in Toggle Button programmatically, how to set id of Toggle Button, how to capitalise text of Toggle Button dynamically etc. We will get answer to all such questions in this post.

Output

Tutorialwing android dynamic toggle button output

Tutorialwing android dynamic toggle button output

Getting Started

We can define android Toggle Button widget as below –

Android toggle button is a widget that are used to display two states(checked/unchecked or ON/OFF) as a button with light indicator and default text ON or OFF.

Now, how do we use Toggle Button in android application ?

Creating New Project

Follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as DynamicToggleButton. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?
Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Toggle Button in Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

Now, we can access view in Kotlin file without using findViewById() method.

Since we have a new project, we will modify the xml and class file to use Toggle Button programmatically in kotlin. Please follow the steps below.

2. Modify Values Folder

Open res/values/strings.xml file. Add below code into it.

Other values folders have not been changed. So, we are not going to mention it here.

3. Modify Layout Folder

Open res/layout/activity_main.xml file. Add below code into it.

Note that LinearLayout has id rootLayout. In Kotlin file, we will create Toggle Button Dynamically and add it into this LinearLayout having id rootLayout.

4. Create Android Toggle Button programmatically in Kotlin

Open src/main/java/com.tutorialwing.dynamictogglebuttonMainActivity.kt file. Then, add below code into it.

Finally, when you run the application, you will get output as shown above.

Tutorialwing android dynamic toggle button output

Tutorialwing android dynamic toggle button output

Now, Let’s check how to use different attributes of Toggle Button to customize it dynamically –

Set Id of Toggle Button

Follow steps below to set id of Toggle Button programmatically –

  • Create ids.xml file in res/values folder. Then, add below code into it –
  • Now, we can set id of Toggle Button dynamically, in MainActivity.kt file, as –

Here, we have set id of Toggle Button using property access syntax – toggleButton.id

Set Width and Height of Toggle Button

We use layoutParams to set width and height of any View programmatically. In this article, we have added Toggle Button in LinearLayout. So, we will define LayoutParams as below –

Here, we have set width and height as WRAP_CONTENT. Some of possible values for width and height are –

  • WRAP_CONTENT: Sets value of width or height depending on text inside it.
  • MATCH_PARENT: Sets value of width of height depending on width or height of parent layout . i.e. width or height of Toggle Button will be same as width or height of parent layout.
  • Fixed Value: Sets width or height as per value provided.

Set Padding of Toggle Button

Follow steps below to set padding of Toggle Button Dynamically –

  • If there is no dimens.xml file, create dimens.xml file in res/values folder. Then, add below code in it –
  • Now, we can set padding of Toggle Button dynamically, in MainActivity.kt file, as –

Here, we have accessed dimension defined in dimens.xml using getDimension() method. Then, set padding of Toggle Button using setPadding() method.

Set Margin of Toggle Button

Follow steps below to set margin of Toggle Button Dynamically –

  • If there is no dimens.xml file, create dimens.xml file in res/values folder. Then, add below code in it –
  • Now, we can set margin of Toggle Button dynamically, in MainActivity.kt file, as –

Here, we have accessed dimension defined in dimens.xml using getDimension() method. Then, we have defined layoutParams, set margin to layoutParams. After that, set layoutParams to ToggleButton

Set Background of Toggle Button

Follow steps below to set background of Toggle Button programmatically –

  • If there is no colors.xml file, create colors.xml file in res/values folder. Then, add below code in it –
  • Now, we can set background of Toggle Button dynamically, in MainActivity.kt file, as –

Here, we used setBackgroundColor() method to set background color in toggleButton.

Set Visibility of Toggle Button

We can set visibility of Toggle Button programmatically as –

Here, we have set visibility of Toggle Button using toggleButton.visibility attribute. Visibility can be of three types – gone, visible and invisible.
Learn to Set Visibility of Toggle Button Using XML Attribute

Set Text of Toggle Button

Follow steps below to set text of Toggle Button programmatically –

  • If there is no strings.xml file, create strings.xml file in res/values folder. Then, add below code in it –
  • Now, we can set text of Toggle Button dynamically, in MainActivity.kt file, as –

Here, we used toggleButton.text to set text in toggleButton.
We can also use toggleButton.textOn and toggleButton.textOff to set text in toggle button when it is ON and OFF states respectively. We can do it as below –

Set Color of Text of Toggle Button

Follow steps below to set color of text of Toggle Button programmatically in Kotlin –

  • If there is no colors.xml file, create colors.xml file in res/values folder. Then, add below code in it –
  • Now, we can set color of text of Toggle Button dynamically, in MainActivity.kt file, as –

Here, we used setTextColor() method to set color of Toggle Button of toggleButton.

Set Gravity of Toggle Button

We can set gravity of text of Toggle Button programmatically in Kotlin as –

Here, we have set gravity of Toggle Button as center. So, all the text of Toggle Button will be center aligned.
We can also apply multiple gravity values as –

Here, we have applied multiple gravity values, in Kotlin, to ToggleButton In above case, text will be aligned as horizontally centered to bottom.
Learn to Set Margin of Toggle Button Using XML Attribute

Set Text in Uppercase or Lowercase

Follow steps below to set text in uppercase or lowercase programmatically as –

Set Text in Uppercase

We use toggleButton.isAllCaps attributes to set text in uppercase or normal. If it is true, text will be set in uppercase.

In Above case, “Hello Tutorialwing” will be set in Uppercase to ToggleButton So, text will be “HELLO TUTORIALWING”.
By default, isAllCaps is false. So, whatever is written, text will be set as it is. For example,

Above code will set text, “Hello Tutorialwing”, to Toggle Button without changing it to Uppercase.

Actually, if isAllCaps is false, text is set as it is. It neither changes to uppercase nor lowercase.

How do we set text in lowercase?
  • In xml file – write all the text in lowercase.
  • In kotlin file – take text as string. Then, convert it in lowercase. Then, set it to toggleButton.

Set Size of Text in Toggle Button

Follow steps below to set size of Toggle Button programmatically using toggleButton.textSize attribute –

  • Open res/values/dimens.xml file. Then, add below font-size in it –
  • Now, using toggleButton.textSize attribute, we can set size of text dynamically as –

Set Style (Bold/italic) of Text in Toggle Button

We can set textStyle of Toggle Button programmatically as –

In above case, we have set textStyle as bold. So, text of Toggle Button will be displayed as bold letters.

If we want to preserve previous textStyle too, we can do it as –

Set Letter Spacing of Text in Toggle Button

Follow steps below to set letter spacing of Toggle Button programmatically –

  • Open res/values/dimens.xml file. Then, add below dimension in it –
  • We use toggleButton.letterSpacing attribute to set letter spacing of Toggle Button as below –

That’s end of tutorial on Toggle Button Programmatically in Kotlin With Example.

Источник

Читайте также:  Где находится пароль от вай фай андроид
Оцените статью