Android 8.0 (API level 26) included a feature which allows you to instruct a TextView to let the text size dynamically expand or contract automatically to fill its layout based on the TextViews characteristics and boundaries. This setting makes it easier to optimize the text size on different screens with dynamic content sizes.
You can implement this feature by using the textview properties given in Android 8.0 (API level 26).
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="60dp">
<!-- Note: If you set autosizing in an XML file, it is not recommended to use the value "wrap_content" for the layout_width attributes of a TextView.It may produce unexpected results. -->
<TextView
android:textSize="30sp"
android:id="@+id/tv_auto_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:autoSizeMaxTextSize="100sp"
android:autoSizeMinTextSize="6sp"
android:autoSizeStepGranularity="2sp"
android:autoSizeTextType="uniform"
android:ellipsize="end"
android:maxLines="1" />
<EditText
android:id="@+id/et_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:maxLines="2" />
</LinearLayout>
Note: If you set autosizing in an XML file, it is not recommended to use the value "wrap_content" for the layout_width or layout_height attributes of a TextView.
It may produce unexpected results.
MainActivity.class
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
EditText editText = findViewById(R.id.et_text);
final TextView textView = findViewById(R.id.tv_auto_text);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable text) {
textView.setText(text.toString());
}
});
}
}
0 Comment(s)