如何在Android的当前屏幕的第一行捕获文本?

时间:2016-04-03 04:53:03

标签: javascript java android android-layout webview

我的项目是电子书阅读器应用程序。屏幕上只有一个VebView,从html文件中获取数据。它只有文字内容。我需要在当前屏幕的第一行获取文本。在下一步中,我需要在文档中找到文本并获取文本在屏幕上的位置。最后,我需要滚动找到的位置。解决该问题所需的所有事情:(WebView Text Zoom Issue in Android

html内容:

<!DOCTYPE html>

    <head>
        <style type="text/css"> 
            p{} p.x1{} p.x2{} p.x3{} p.x4{} 
            h2.x1{} h2.x2{} h2.x3{} h2.x4{}
        </style>
    </head>

    <body>

        //paragraph-1
        <p class="x1">Title-1</p>
        <p class="x2">Title-2</p>
        <p class="x3">Title-3</p>
        <p class="x4">Title-4</p>
        <p>Text content.</p>


        //paragraph-2
        <h class="x1">Title-1</p>
        <h class="x2">Title-2</p>
        <p>Text content.</p>


        //paragraph-3
        <h class="x3">Title-1</p>
        <h class="x4">Title-2</p>
        <p class="x3">Title-3</p>
        <p>Text content.</p>


        //paragraph-4
        <h class="x2">Title-1</p>
        <p class="x3">Title-2</p>
        <p>Text content.</p>


        //...

    </body>

</html>

2 个答案:

答案 0 :(得分:1)

没有直接的方法可以做你想要的, 首先通过

获取html内容
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);

String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
    str.append(line);
}
in.close();
html = str.toString();

然后使用子字符串conccept来获得你想要的东西,看看Get Html content

或者您可以使用Jsoap parser 从HTML

中的指定标记获取值
Document doc=Jsoup.connect("http://www.yahoo.com").get();
Elements elements=doc.select("img");

for(Element e:elements)
 {
  System.out.println(e.attr("src"));
 }

答案 1 :(得分:1)

我认为你在寻找这个?

function findTopObject (elements) {
    var top = Number.POSITIVE_INFINITY;
    var obj = null;

    Array.from(elements).forEach(function (o) {
        var t = o.getBoundingClientRect(o).top;
        if (t > 0.0 && top > t) {
            obj = o;
            top = t;
        }
    });

    return obj;
}

for (var i = 0; i < 1000; i++) {
  var p = document.createElement("p");
  p.innerText = "Line " + i;
  document.body.appendChild(p);
}

var elements = document.querySelectorAll("p");
var obj = null;

window.onscroll = function() {
  if (obj != null) {
    obj.style.backgroundColor = "";
  }

  obj = findTopObject(elements);

  if (obj != null) {
    obj.style.backgroundColor = "red";
  }
};

function findTopObject(elements) {
  var top = Number.POSITIVE_INFINITY;
  var obj = null;
  Array.from(elements).forEach(function(o) {
    var t = o.getBoundingClientRect(o).top;
    if (t > 0.0 && top > t) {
      obj = o;
      top = t;
    }
  });
  return obj;
}
<body></body>