I have a vertical LinearLayout with a height of 32dp and i want to fit two TextView of 16dp each. The length of the text is different and i want it to always nicely fit in a single line.
I have tried with an AutoTextView and with a classic TextView + AutoSizing by TextViewCompat but none of these really work. My text shrink a bit but always finish to be crop at the bottom.
Here the base code
LinearLayout adressTextLayout = new LinearLayout(activity);
adressTextLayout.setOrientation(LinearLayout.VERTICAL);
adressTextLayout.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
//icon_size_big = 32dp
(int) (activity.getResources().getDimension(R.dimen.icon_size_big))));
boolean noAdress = true;
//First line with Country, Region and department
if(!mondialAdress.isEmpty()){
noAdress = false;
TextView tx = Utils.createAutoFitTextView(activity, mondialAdress, true, (int) (activity.getResources().getDimension(R.dimen.icon_size_big)/2));
tx.setTypeface(null, Typeface.ITALIC);
adressTextLayout.addView(tx);
}
//Second line with adress, postal code and city
if(!localAdress.isEmpty()){
noAdress = false;
TextView tx = Utils.createAutoFitTextView(activity, localAdress, true, (int) (activity.getResources().getDimension(R.dimen.icon_size_big)/2));
adressTextLayout.addView(tx);
}
//Default line in case we didn't found any adress
if(noAdress){
adressTextLayout.addView(Utils.createAutoFitTextView(activity, activity.getResources().getString(R.string.hint_provide_information), true, 0));
}
Here is the createAutoFitTextView() function with TextViewCompat
public static TextView createAutoFitTextView(Activity activity, String text, boolean singleLine, int maxHeight) {
TextView textView = new AutofitTextView(activity);
textView.setText(text);
//MATCH_PARENT by default
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, maxHeight > 0 ? maxHeight : ViewGroup.LayoutParams.MATCH_PARENT);
textView.setLayoutParams(params);
//Auto Sizing by TextViewCompat
TextViewCompat.setAutoSizeTextTypeWithDefaults(textView, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
if(singleLine){
textView.setSingleLine(true);
}
return textView;
}
Here the function with AutoFitTextView
public static AutofitTextView createAutoFitTextView(Activity activity, String text, boolean singleLine, int maxHeight) {
AutofitTextView textView = new AutofitTextView(activity);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, maxHeight != -1 ? maxHeight : ViewGroup.LayoutParams.MATCH_PARENT);
textView.setLayoutParams(params);
textView.setText(text);
if(singleLine){
textView.setSingleLine(true);
}
return textView;
}
Here a the result :
With TextViewCompat
With AutoFillTextView: