I want to know if I have a text like "hello world". How can I set the preference of this text view that user can change the font size to medium, large and small like 20sp, 25sp, 30sp.
Asked
Active
Viewed 292 times
1 Answers
0
If you have an activity, which layout have a
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World"
android:textSize="20sp"
/>
so, you need an user input like buttons and in the activity you can changue the size of the textview element detecting an event relate to the user input, in this example the "onclick" method.
here is the code to archieve that.
layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txt_hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="HelloWorld"
android:textColor="@android:color/black"
android:textSize="20sp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/txt_hello_world"
android:orientation="horizontal"
>
<Button
android:id="@+id/btn_20sp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="8dp"
android:text="20sp"
/>
<Button
android:id="@+id/btn_30sp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="8dp"
android:text="30sp"
/>
<Button
android:id="@+id/btn_40sp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="8dp"
android:text="40sp"
/>
</LinearLayout>
Activity
class MainActivity : AppCompatActivity(), View.OnClickListener {
lateinit var helloText : TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
helloText = findViewById(R.id.txt_hello_world)
var btn20sp: Button = findViewById(R.id.btn_20sp)
btn20sp.setOnClickListener(this)
var btn30sp: Button = findViewById(R.id.btn_30sp)
btn30sp.setOnClickListener(this)
var btn40sp: Button = findViewById(R.id.btn_40sp)
btn40sp.setOnClickListener(this)
}
override fun onClick(view: View) {
when (view.id){
R.id.btn_20sp -> helloText.setTextSize(TypedValue.COMPLEX_UNIT_SP,20f)
R.id.btn_30sp -> helloText.setTextSize(TypedValue.COMPLEX_UNIT_SP,30f)
R.id.btn_40sp -> helloText.setTextSize(TypedValue.COMPLEX_UNIT_SP,40f)
}
}
}
The code is in kotlin but the logic is the samen in java

Jhon Fredy Trujillo Ortega
- 478
- 4
- 12
-
-
i will apreciate if you selecte this like correct answer, thank you. – Jhon Fredy Trujillo Ortega Jan 18 '18 at 14:18