それは私の神経質になっていました、私はそれを認めます。私は、コード内でを次のTextViews
ように表示するのが好きです。また、テキスト整列: 正当化された書式設定を実現する手段として a を使用している場合でも、そのように見たくありません。TextViews
WebView
TextView
から一般的に使用するメソッドを実装し、それらの変更を反映するために WebView のコンテンツを変更するカスタム ビュー (醜い、おそらく悪い) を作成しました。それが他の誰かにとって有用であるか、それとも私が本当に知らない潜在的な危険性であるかにかかわらず、私にとっては機能し、いくつかのプロジェクトで使用しましたが、問題は発生していません. 唯一の小さな不都合は、メモリ的にはより大きな通行料であると想定していることですが、それが 1 つまたは 2 つだけの場合は心配する必要はありません (間違っている場合は修正してください)。
結果は次のとおりです。

プログラムで設定するためのコードは、次のように単純です。
JustifiedTextView J = new JustifiedTextView();
J.setText("insert your text here");
もちろん、そのままにしておくのはばかげているので、基本的に TextViews を使用するすべてである font-size と font-color を変更するためのメソッドも追加しました。つまり、次のようなことができます。
JustifiedTextView J = new JustifiedTextView();
J.setText("insert your text here");
J.setTextColor(Color.RED);
J.setTextSize(30);
次の結果が得られます (画像はトリミングされています)。

しかし、これは私たちにそれがどのように見えるかを示すことではなく、あなたがそれをどのように行ったかを共有することです.
分かってる。これが完全なコードです。また、透明な背景を設定し、UTF-8 文字列をビューにロードする際の問題にも対処します。詳細については、reloadData() のコメントを参照してください。
public class JustifiedTextView extends WebView{
private String core = "<html><body style='text-align:justify;color:rgba(%s);font-size:%dpx;margin: 0px 0px 0px 0px;'>%s</body></html>";
private String textColor = "0,0,0,255";
private String text = "";
private int textSize = 12;
private int backgroundColor=Color.TRANSPARENT;
public JustifiedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setWebChromeClient(new WebChromeClient(){});
}
public void setText(String s){
this.text = s;
reloadData();
}
@SuppressLint("NewApi")
private void reloadData(){
// loadData(...) has a bug showing utf-8 correctly. That's why we need to set it first.
this.getSettings().setDefaultTextEncodingName("utf-8");
this.loadData(String.format(core,textColor,textSize,text), "text/html","utf-8");
// set WebView's background color *after* data was loaded.
super.setBackgroundColor(backgroundColor);
// Hardware rendering breaks background color to work as expected.
// Need to use software renderer in that case.
if(android.os.Build.VERSION.SDK_INT >= 11)
this.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
}
public void setTextColor(int hex){
String h = Integer.toHexString(hex);
int a = Integer.parseInt(h.substring(0, 2),16);
int r = Integer.parseInt(h.substring(2, 4),16);
int g = Integer.parseInt(h.substring(4, 6),16);
int b = Integer.parseInt(h.substring(6, 8),16);
textColor = String.format("%d,%d,%d,%d", r, g, b, a);
reloadData();
}
public void setBackgroundColor(int hex){
backgroundColor = hex;
reloadData();
}
public void setTextSize(int textSize){
this.textSize = textSize;
reloadData();
}
}