テーマとWebViewの背景色を同じにする
目的
背景色を決めうちにせず、できることならWebViewとテーマと連動した配色にする。
コード
getHTMLで取得した内容をそのままWebViewに食わせてあげれば、背景色等が同化した形にできる。
呼び出し部分
protected void setTextileText(WebView v,String text){ v.loadDataWithBaseURL("", ConvertTextUtil.getHtml(v.getContext(),text,""), "text/html", "UTF-8", ""); }
該当処理部分(ConvertTextUtil)
static public String getHtml(Context context,String innerhtml,String headerhtml){ StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\" ?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head>"); sb.append(headerhtml); sb.append("</head>"); sb.append("<body"); sb.append(" bgcolor=\"#" + getRGBString(getBackgroundColor(context)) + "\""); sb.append(" text=\"#" + getRGBString(getFontColor(context)) + "\""); sb.append(" style=\"margin:0;\""); sb.append(">"); sb.append(innerhtml); sb.append("</body></html>"); return sb.toString(); } static public int getAttribute(Context context,int target){ TypedValue typedValue = new TypedValue(); context.getTheme().resolveAttribute(target, typedValue, true); int resourceId = typedValue.resourceId; return context.getResources().getColor(resourceId); } static public String getRGBString(int color){ //ARGBとなっているため、アルファ部分に値が存在するようにすることで、rgbのみを切り出せるようにする。 String hex = Integer.toHexString(0xFF000000 | color); return hex.substring(hex.length()-6); } static public int getBackgroundColor(Context context){ return getAttribute(context, android.R.attr.colorBackground); } static public int getFontColor(Context context){ return getAttribute(context, android.R.attr.colorForeground); }