Reputation: 11665
I have a webview on my 4.1.2 Android, which I load with
public class FullscreenActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
final WebView wv=(WebView)findViewById(R.id.webView1);
String sHTML="Webviewtest";
for(int i=0;i<500;i++){
sHTML=sHTML+"Line " + i + "<br>";
}
wv.loadData(sHTML, "text/html", null);
wv.setScrollY(1500);
wv.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
wv.setScrollY(500);
Toast.makeText(getApplicationContext(), "Done! " + wv.getScrollY(), Toast.LENGTH_SHORT).show();
}
});
}
}
I like the webview to scroll down to a specific postition, but it stays on the top. any ideas ? When setScrollY() with a button it works, but I like to set the position after laoding the HTML. I also tried to do it with a Handler, which I call in onPageFinished. This does not work too.
I created a very simple Android project, where everyone can download and test: https://drive.google.com/folderview?id=0B7yz_IQ1CMblUU03cGd5cEotTVE&usp=sharing
Upvotes: 0
Views: 2091
Reputation: 662
WebView.setScrollY works for me only when I give it some delay with a timer after the WebView is loaded:
webView.loadData(sHtmlTemplate, "text/html", "utf-8");
Timer t = new Timer(false);
t.schedule(new TimerTask() {
@Override
public void run() {
MainActivity.mainactivity.runOnUiThread(new Runnable() {
public void run() {
webView.setScrollY(500);
}
});
}
}, 300); // 300 ms delay before scrolling
Upvotes: 0
Reputation: 750
This time it is not android's fault,it has provided us with another approach.
try:
public void onPageFinished(WebView v, String url) {
v.evaluateJavascript("window.scrollTo(0,"+expectedPos/a.getResources().getDisplayMetrics().density+");", null);
super.onPageFinished(v, url);
}
Upvotes: 2
Reputation: 11665
My Solution. I don't like it, but it works. All this mess because of the android framework, that doesn't work like expected...
I added a AsyncTask:
private class Waitforloaded extends AsyncTask<String, Integer, Long> {
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
@Override
protected Long doInBackground(String... params) {
// TODO Auto-generated method stub
boolean bgo=true;
int iTries=0;
while(bgo){
iTries=iTries+1;
if(iTries>20 || wv.getContentHeight()>0){
bgo=false;
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
wv.setScrollY(1500);
return null;
}
}
Then calling it in
wv.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Waitforloaded wfl=new Waitforloaded();
wfl.execute("");
}
Upvotes: 0