androidstringhtml
A. 如何實現在Android TextView中捕獲鏈接的點擊事件
Android中的TTextView很強大,我們可以不僅可以設置純文本為其內容,還可以設置包含網址和電子郵件地址的內容,並且使得這些點擊可以點擊。但是我們可以捕獲並控制這些鏈接的點擊事件么,當然是可以的。
本文將一個超級簡單的例子介紹一下如何實現在Android TextView捕獲鏈接的點擊事件。
關鍵實現
實現原理就是將所有的URL設置成ClickSpan,然後在它的onClick事件中加入你想要的控制邏輯就可以了。
復制代碼代碼如下:
private void setLinkClickable(final SpannableStringBuilder clickableHtmlBuilder,
final URLSpan urlSpan) {
int start = clickableHtmlBuilder.getSpanStart(urlSpan);
int end = clickableHtmlBuilder.getSpanEnd(urlSpan);
int flags = clickableHtmlBuilder.getSpanFlags(urlSpan);
ClickableSpan clickableSpan = new ClickableSpan() {
public void onClick(View view) {
//Do something with URL here.
}
};
clickableHtmlBuilder.setSpan(clickableSpan, start, end, flags);
}
private CharSequence getClickableHtml(String html) {
Spanned spannedHtml = Html.fromHtml(html);
SpannableStringBuilder clickableHtmlBuilder = new SpannableStringBuilder(spannedHtml);
URLSpan[] urls = clickableHtmlBuilder.getSpans(0, spannedHtml.length(), URLSpan.class);
for(final URLSpan span : urls) {
setLinkClickable(clickableHtmlBuilder, span);
}
return clickableHtmlBuilder;
}
如何使用
復制代碼代碼如下:
TextView myTextView = (TextView)findViewById(R.id.myTextView);
String url = "This is a page with lots of URLs. <a href=\"http://jb51.net\">jb51.net</> " +
"This left is a very good blog. There are so many great blogs there. You can find what" +
"you want in that blog."
+ "The Next Link is <a href=\"http://www.google.com.hk\">Google HK</a>";
myTextView.setText(getClickableHtml(url));
實現自己的控制
我們需要在ClickSpan的onClick方法中加入自己的控制邏輯,比如我們使用傲遊瀏覽器打開點擊的鏈接。
復制代碼代碼如下:
public void onClick(View view) {
Log.i(LOGTAG, "onClick url=" + urlSpan.getURL() );
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(urlSpan.getURL()));
intent.setPackage("com.mx.browser");
startActivity(intent);
}
提醒
不要忘了設置TextView的autoLink屬性。
復制代碼代碼如下:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:id="@+id/myTextView"
android:autoLink="web"
/>
B. Android如何獲取html格式化之前的字元串
java中String 類有一個方法為substring(int beginIndex, int endIndex),它返回一個新字元串,它是此字元串從指定的
beginIndex處開始,一直到索引 endIndex - 1處的字元組成的新字元串。因此,該子字元串的長度為 endIndex-beginIndex
。
String a="a796Fb28@";
String b=a.substring(0,5);
則b返回值為a796F。
C. Android 在strings.xml中定義html標簽
第二種情況 Android在通過Context.getString獲取字元串時做了處理,把Html標記都去掉了,這個可以把斷點跟蹤一下。所以第二種情況沒有傾斜加粗的效果。
第二種情況這么修改就有效果了:
textView.setText(this.getText(R.string.tagged_string));
這也說明了Context.getText 和 Context.getString的區別。
D. android 獲取網頁指定內容
android也是用的java語言,使用java中的字元串方法就能實現想要的功能
E. android 怎樣用html文件
html頁面(命名:Android.html放在assets文件夾下):::::
<!DOCTYPEhtmlPUBLIC"-//WAPFORUM//DTDXHTMLMobile1.0//EN""
<htmlxmlns="">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<scriptlanguage="javascript"type="text/javascript">
functionget4Android(str){
document.getElementById("show").innerHTML="Thisisamessagefromandroid:"+str;
}
</script>
</head>
<body>
<divid="show"></div>
</body>
</html>
Text.java代碼:::
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.text.Editable;
importandroid.view.MotionEvent;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.view.View.OnTouchListener;
importandroid.webkit.WebSettings;
importandroid.webkit.WebView;
importandroid.webkit.WebViewClient;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.TextView;
{
privateButtonbutton;
privateTextViewtext;
privateWebViewweb;
privateEditTextedit;
privateHandlerhandler;
privatevoidinitView(){
button=(Button)this.findViewById(R.id.button2);
web=(WebView)this.findViewById(R.id.webView1);
edit=(EditText)this.findViewById(R.id.editText1);
button.setOnClickListener(this);
}
privatevoidsetWebView(){
web.setWebViewClient(newWebViewClient());
web.requestFocus();
WebSettingssetting=web.getSettings();
setting.setJavaScriptEnabled(true);
web.setOnTouchListener(newOnTouchListener(){
@Override
publicbooleanonTouch(Viewv,MotionEventevent){
web.requestFocus();
returnfalse;
}
});
web.addJavascriptInterface(newSendAndroid(),"theKey");
web.loadUrl("file:///android_asset/android.html");
}
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
setWebView();
handler=newHandler(){
publicvoidhandleMessage(android.os.Messagemsg){
Stringstr=msg.obj.toString();
text.setText(str);
};
};
}
@Override
publicvoidonClick(Viewv){
Editableeditable=edit.getText();
web.loadUrl("javascript:get4Android(""+editable.toString()
+"")");
}
classSendAndroid{
(finalStringstr){
newThread(newRunnable(){
@Override
publicvoidrun(){
System.out.println("******"+str);
Messagemes=handler.obtainMessage();
mes.obj=str;
handler.sendMessage(mes);
}
}).start();
}
}
}
主要是:web.loadUrl("javascript:get4Android(""+editable.toString()+"")");中的「javascript:get4Android」要和html中的【functionget4Android(str){
document.getElementById("show").innerHTML="Thisisamessagefromandroid:"+str;
}】方法名相同
F. android裡面怎麼加html文件
html頁面(命名:Android.html放在assets文件夾下):::::
<!DOCTYPEhtmlPUBLIC"-//WAPFORUM//DTDXHTMLMobile1.0//EN""
<htmlxmlns="">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<scriptlanguage="javascript"type="text/javascript">
functionget4Android(str){
document.getElementById("show").innerHTML="Thisisamessagefromandroid:"+str;
}
</script>
</head>
<body>
<divid="show"></div>
</body>
</html>
Text.java代碼:::
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.text.Editable;
importandroid.view.MotionEvent;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.view.View.OnTouchListener;
importandroid.webkit.WebSettings;
importandroid.webkit.WebView;
importandroid.webkit.WebViewClient;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.TextView;
{
privateButtonbutton;
privateTextViewtext;
privateWebViewweb;
privateEditTextedit;
privateHandlerhandler;
privatevoidinitView(){
button=(Button)this.findViewById(R.id.button2);
web=(WebView)this.findViewById(R.id.webView1);
edit=(EditText)this.findViewById(R.id.editText1);
button.setOnClickListener(this);
}
privatevoidsetWebView(){
web.setWebViewClient(newWebViewClient());
web.requestFocus();
WebSettingssetting=web.getSettings();
setting.setJavaScriptEnabled(true);
web.setOnTouchListener(newOnTouchListener(){
@Override
publicbooleanonTouch(Viewv,MotionEventevent){
web.requestFocus();
returnfalse;
}
});
web.addJavascriptInterface(newSendAndroid(),"theKey");
web.loadUrl("file:///android_asset/android.html");
}
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
setWebView();
handler=newHandler(){
publicvoidhandleMessage(android.os.Messagemsg){
Stringstr=msg.obj.toString();
text.setText(str);
};
};
}
@Override
publicvoidonClick(Viewv){
Editableeditable=edit.getText();
web.loadUrl("javascript:get4Android(""+editable.toString()
+"")");
}
classSendAndroid{
(finalStringstr){
newThread(newRunnable(){
@Override
publicvoidrun(){
System.out.println("******"+str);
Messagemes=handler.obtainMessage();
mes.obj=str;
handler.sendMessage(mes);
}
}).start();
}
}
}
主要是:web.loadUrl("javascript:get4Android(""+editable.toString()+"")");中的「javascript:get4Android」要和html中的【functionget4Android(str){
document.getElementById("show").innerHTML="Thisisamessagefromandroid:"+str;
}】方法名相同
G. Android 中 Webview 怎麼獲取打開的網頁的 HTML 代碼
WebView(網路視圖)能載入顯示網頁,可以將其視為一個瀏覽器。它使用了WebKit渲染引擎載入顯示網頁,實現WebView有以下兩種不同的方法:
第一種方法的步驟:
1.在要Activity中實例化WebView組件:WebView webView = new WebView(this);
2.調用WebView的loadUrl()方法,設置WevView要顯示的網頁:
互聯網用:webView.loadUrl("http://網址");
本地文件用:webView.loadUrl("file:///android_asset/XX.html"); 本地文件存放在:assets 文件中
3.調用Activity的setContentView( )方法來顯示網頁視圖
4.用WebView點鏈接看了很多頁以後為了讓WebView支持回退功能,需要覆蓋覆蓋Activity類的onKeyDown()方法,如果不做任何處理,點擊系統回退剪鍵,整個瀏覽器會調用finish()而結束自身,而不是回退到上一頁面
5.需要在AndroidManifest.xml文件中添加許可權,否則會出現Web page not available錯誤。
<uses-permission android:name="android.permission.INTERNET" />
第二種方法的步驟:
1、在布局文件中聲明WebView
2、在Activity中實例化WebView
3、調用WebView的loadUrl( )方法,設置WevView要顯示的網頁
4、為了讓WebView能夠響應超鏈接功能,調用setWebViewClient( )方法,設置 WebView視圖
5、用WebView點鏈接看了很多頁以後為了讓WebView支持回退功能,需要覆蓋覆蓋Activity類的onKeyDown()方法,如果不做任何處理,點擊系統回退剪鍵,整個瀏覽器會調用finish()而結束自身,而不是回退到上一頁面
6、需要在AndroidManifest.xml文件中添加許可權,否則出現Web page not available錯誤。
<uses-permission android:name="android.permission.INTERNET"/>
H. android如何保存html文件,包括其中的圖片。
1、先示例圖片
2、操作代碼
package com.nekocode.xue.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.nekocode.xue.PublicData;
import com.nekocode.xue.PublicData.Subscribe;
public class HtmlStorageHelper {
private String URL = "http://eproject.sinaapp.com/fetchurl.php/getcontent/";
private PublicData pd;
private AQuery aq;
private SQLiteDatabase mDB;
private String mDownloadPath;
public HtmlStorageHelper(Context context) {
pd = PublicData.getInstance();
aq = new AQuery(context);
mDB = context.openOrCreateDatabase("data.db", Context.MODE_PRIVATE, null);
mDB.execSQL("create table if not exists download_html(_id INTEGER PRIMARY KEY AUTOINCREMENT, content_id TEXT NOT NULL, title TEXT NOT NULL)");
mDownloadPath = pd.mAppPath + "download/";
File dir_file = new File(pd.mAppPath + "download/");
if(!dir_file.exists())
dir_file.mkdir();
}
public void saveHtml(final String id, final String title) {
if(isHtmlSaved(id))
return;
aq.ajax(URL+id, String.class, new AjaxCallback<String>() {
@Override
public void callback(String url, String html, AjaxStatus status) {
File dir_file = new File(mDownloadPath + id);
if(!dir_file.exists())
dir_file.mkdir();
Pattern pattern = Pattern.compile("(?<=src=")[^"]+(?=")");
Matcher matcher = pattern.matcher(html);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
downloadPic(id, matcher.group(0));
matcher.appendReplacement(sb, formatPath(matcher.group(0)));
}
matcher.appendTail(sb);
html = sb.toString();
writeHtml(id, title, html);
}
});
}
private void downloadPic(String id, String url) {
File pic_file = new File(mDownloadPath + id + "/" + formatPath(url));
aq.download(url, pic_file, new AjaxCallback<File>() {
@Override
public void callback(String url, final File file, AjaxStatus status) {
}
});
}
private void writeHtml(String id, String title, String html) {
File html_file = new File(mDownloadPath + id + "/index.html");
FileOutputStream fos = null;
try {
fos=new FileOutputStream(html_file);
fos.write(html.getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fos.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
ContentValues values = new ContentValues();
values.put("content_id", id);
values.put("title", title);
mDB.insert("download_html", "_id", values);
}
public boolean isHtmlSaved(String id) {
File file = new File(mDownloadPath + id);
if(file.exists()) {
file = new File(mDownloadPath + id + "/index.html");
if(file.exists())
return true;
}
deleteHtml(id);
return false;
}
public String getTitle(String id) {
Cursor c = mDB.rawQuery("select * from download_html where content_id=?", new String[]{id});
if(c.getCount() == 0)
return null;
c.moveToFirst();
int index1 = c.getColumnIndex("title");
return c.getString(index1);
}
public ArrayList<Subscribe> getHtmlList() {
Cursor c = mDB.rawQuery("select * from download_html", null);
ArrayList<Subscribe> list = new ArrayList<Subscribe>();
if(c.getCount() != 0) {
c.moveToFirst();
int index1 = c.getColumnIndex("content_id");
int index2 = c.getColumnIndex("title");
while (!c.isAfterLast()) {
String id = c.getString(index1);
if(isHtmlSaved(id)) {
Subscribe sub = new Subscribe(
id,
c.getString(index2),
Subscribe.FILE_DOWNLOADED
);
list.add(sub);
}
c.moveToNext();
}
}
return list;
}
public void deleteHtml(String id) {
mDB.delete("download_html", "content_id=?", new String[]{id});
File dir_file = new File(mDownloadPath + id);
deleteFile(dir_file);
}
private void deleteFile(File file) {
if (file.exists()) { // 判斷文件是否存在
if (file.isFile()) { // 判斷是否是文件
file.delete(); // delete()方法 你應該知道 是刪除的意思;
} else if (file.isDirectory()) { // 否則如果它是一個目錄
File files[] = file.listFiles(); // 聲明目錄下所有的文件 files[];
for (int i = 0; i < files.length; i++) { // 遍歷目錄下所有的文件
this.deleteFile(files[i]); // 把每個文件 用這個方法進行迭代
}
}
file.delete();
} else {
//
}
}
private String formatPath(String path) {
if (path != null && path.length() > 0) {
path = path.replace("\", "_");
path = path.replace("/", "_");
path = path.replace(":", "_");
path = path.replace("*", "_");
path = path.replace("?", "_");
path = path.replace(""", "_");
path = path.replace("<", "_");
path = path.replace("|", "_");
path = path.replace(">", "_");
}
return path;
}
}
3、這段代碼簡單修改就可以用到自己的項目中了
I. 請問如何用android解析html格式的字元串,並顯示在一般控制項中
private void loadHTML(){
String html = "<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
" <title></title>\n" +
"</head>\n" +
"<body>\n" +
" Hello!耶耶耶<br/>\n" +
"HTML Page here!\n" +
"<img src=\"img/bdlogo.gif\"></im>\n" +
"</body>\n" +
"</html>";
webView.loadData(html, "text/html", "UTF-8");
// webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
}
J. android中如何在textview中加入html
具體代碼如下:
Android中的TextView,本身就支持部分的Html格式標簽。這其中包括常用的字體大小顏色設置,文本鏈接等。使用起來也比較方便,只需要使用Html類轉換一下即可。比如:
textView.setText(Html.fromHtml(str));
然而,有一種場合,默認支持的標簽可能不夠用。比如,我們需要在textView中點擊某種鏈接,返回到應用中的某個界面,而不僅僅是網路連接,如何實現?
經過幾個小時對android中的Html類源代碼的研究,找到了解決辦法,並且測試通過。