我正在寻找一种简单的方法来忘记我正在使用 WebView
在我的 TextView
中对齐文本。有人为此制作了自定义 View 吗?我很清楚我可以做这样的事情:
WebView view = new WebView(this);
view.loadData("my html with text justification","text/html","utf-8");
但是当您想要设置 TextView
的大小、颜色或其他常见属性时,它会变得很丑陋。一定有更方便的方法。
最佳答案
这让我很紧张,我承认。我喜欢 TextViews
在代码中看起来像 TextViews
,即使我使用 WebView
作为实现文本的方式- align:justified formatting,我不想这样看。
我创建了一个自定义 View (丑陋,可能很糟糕),它实现了我在 TextView
中常用的方法,并修改了 WebView 的内容以反射(reflect)这些更改。
无论它对其他人有用还是我真的不知道的潜在危险,对我来说它都有效,我已经在几个项目中使用过它并且没有遇到任何问题。唯一的小不便是我认为它是一个更大的内存损失,但如果它只是一个或两个则无需担心(如果我错了请纠正我)。
结果如下:
以编程方式设置它的代码就这么简单:
JustifiedTextView J = new JustifiedTextView();
J.setText("insert your text here");
当然,就这样保留它是愚蠢的,所以我还添加了更改字体大小和字体颜色的方法,这些基本上都是我使用 TextViews 的目的。这意味着我可以做这样的事情:
JustifiedTextView J = new JustifiedTextView();
J.setText("insert your text here");
J.setTextColor(Color.RED);
J.setTextSize(30);
并得到如下结果(图片被裁剪):
但是,这并不是要向我们展示它的外观,而是要分享您是如何做到的!
我知道,我知道。 这是完整的代码。它还解决了设置透明背景和将 UTF-8 字符串加载到 View 中时出现的问题。有关详细信息,请参阅 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();
}
}
关于android - 使用 WebView 在 Android 应用程序中对齐文本但呈现类似 TextView 的界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11922861/