In this tutorial, we will discuss Custom Component in Android Programmatically. We can add TextView, Edittext,Datepicker, Timepickerr and many more.Let’s code and discuss how we can implement it programmatically.
MainActivity
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package com.example.customattribute import android.app.DatePickerDialog import android.os.Bundle import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.AppCompatEditText import java.text.SimpleDateFormat import java.util.* class MainActivity : AppCompatActivity() { lateinit var linearLayout:LinearLayout; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) linearLayout=findViewById(R.id.ll) addEditTextView() addTextView() datePickerDialog() } private fun addEditTextView() { val edt = AppCompatEditText(this) edt.hint = "please input something" linearLayout.addView(edt) } private fun addTextView(){ val tv=TextView(this) tv.setText("Text view") linearLayout.addView((tv)) } private fun datePickerDialog(){ val myCalendar = Calendar.getInstance() val btn=Button(this) btn.text="date picker" val tv=TextView(this) val date1 = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> myCalendar.set(Calendar.YEAR, year) myCalendar.set(Calendar.MONTH, monthOfYear) myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth) val myFormat = "dd/MM/yy" val sdf = SimpleDateFormat(myFormat, Locale.US) tv.text = sdf.format(myCalendar.time) } btn.setOnClickListener { DatePickerDialog(this, date1, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show() } linearLayout.addView(btn) linearLayout.addView(tv) } } |
As you can see we have added 3 views. TextView,EditText and DatePickerDialog.
For TextView we created a view from Textview and added it to Linearlayout and same did for EditText.
For DatePickerDialog we create an instance of Calendar and created a button. After opening DatePicker Dialog we select date and show in Textview.
activity_main
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:id="@+id/ll" android:orientation="vertical" android:layout_height="match_parent" tools:context=".MainActivity"> </LinearLayout> |
please check screenshot how it shows
So Here we discussed Custom Component in Android Programmatically. Thanks for reading this blog and You can get other blogs from here