毎回layoutのxmlに設定するのがめんどう…
以前投稿した下記2件についてTextViewを利用する際に毎回設定を書くのがめんどう…
Android Pie対応するときにTextViewの改行の行間でハマった話
Android8.0でTextViewに表示した文字列の折り返し位置がおかしい
と言うわけで
問題を気にせずに利用できるCustomTextViewを作成してみた、実際のコードが下記
import android.content.Context;
import android.os.Build;
import android.text.Layout;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatTextView;
public class CustomTextView extends AppCompatTextView {
public CustomTextView(Context context) {
this(context, null);
}
public CustomTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
versionDifferenceAbsorption();
}
/**
* ここでバージョン毎で起こっている問題が起こらないように設定を行う
*/
private void versionDifferenceAbsorption() {
// Android8.0の場合にはBreakStrategyをsimpleに設定する
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {
this.setBreakStrategy(Layout.BREAK_STRATEGY_SIMPLE);
}
// Android9.0以降ではFallbackLineSpacingをfalseに設定する
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
this.setFallbackLineSpacing(false);
}
}
}
さっそく動かしてみた
Android9.0側で表示を試したxmlの設定
<CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="君がッ\n泣くまで\n殴るのを\nやめないッ!"
android:lineSpacingMultiplier="1.5"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Android8.0側で表示を試したxmlの設定
<CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="さすがディオ!俺達に出来ないことを平然とやってのけるッ!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
デフォルトのTextViewで表示したAndroid 9のEmulator![]() |
カスタムのTextViewで表示したAndroid 9のEmulator![]() |
デフォルトのTextViewで表示したAndroid 8.0のEmulator![]() |
カスタムのTextViewで表示したAndroid 8.0のEmulator![]() |
表示を確認した結果!
Android9.0側は行間が開かず、Android8.0側は改行位置がおかしくなっていないので、最低限以前投稿した内容の問題は起こらない様子
今後は今回作成したCustomTextViewを利用することで問題を気にせずに実装したい