MainActivity.kt
package com.example.jetpack
import android.content.Context
import android.os.Bundle
import android.util.TypedValue
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val context = this
val string = "Lorem Ipsum is simply dummy text of the printing" +
" and typesetting industry."
textView.text = string
// set text view layout margin programmatically
(textView.layoutParams as ConstraintLayout.LayoutParams).apply {
// individually set text view any side margin
marginStart = 25.dpToPixels(context)
topMargin = 35.dpToPixels(context)
marginEnd = 50.dpToPixels(context)
// or set margins in this way
/*setMargins(
25.dpToPixels(context), // left/start margin
35.dpToPixels(context), // top margin
50.dpToPixels(context), // right/end margin
0 // bottom margin
)*/
}
}
}
// extension function to convert dp to equivalent pixels
fun Int.dpToPixels(context: Context):Int = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,this.toFloat(),context.resources.displayMetrics
).toInt()
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#EDEAE0"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#DC143C"
android:textColor="#FFFDD0"
tools:text="Sample TextView"
android:textSize="30sp"
android:padding="25dp"
android:textStyle="italic"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

- android kotlin - Create TextView programmatically
- android kotlin - TextView add Hyperlink programmatically
- android kotlin - TextView get width height programmatically
- android kotlin - TextView html formatted text
- android kotlin - Coroutines with timeout or null
- android kotlin - Coroutines async with timeout
- android kotlin - Coroutines with timeout
- android kotlin - Coroutines with ViewModel LiveData
- android kotlin - Coroutines Room ViewModel LiveData
- android kotlin - Room with coroutines
- android kotlin - Coroutines download image from url
- android kotlin - Coroutines url to bitmap
- android kotlin - Coroutines async
- android kotlin - Paint linear gradient
- android kotlin - Paint gradient circle