In this post we will how to create TextView in xml layout and dynamically Creating In Kotlin
String
<resources> <string name="app_name">AndroidTextView</string> <string name="label">TextView</string> <string name="dynaamic_textview">Dynamic TextView</string> </resources>
1. TextView In XML
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" android:gravity="center" android:id="@+id/rootLayout"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/label" android:textSize="22sp"/> </LinearLayout>
2. Creating TextView programmatically in kotlin
- Create a object TextView .
- Set LayoutParams (Width and height) .
- Add Text to TextView by calling setText .
- To set size call setTextSize ( first param for unit and second param size ).
package com.tutorialsbuzz.androidtextview import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.TypedValue import android.view.ViewGroup import android.widget.TextView import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val textView = TextView(this); textView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) textView.setText(R.string.dynaamic_textview); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,22f); rootLayout.addView(textView); } }
No comments:
Post a Comment