【www.bbyears.com--说说】
我们浏览淘宝商品详情的时候会遇到回到顶部这个功能,下面就说说这个功能的简单实现
<frameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent" >
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true" >
android:layout_height="match_parent"
android:orientation="vertical" >
android:layout_width="match_parent"
android:layout_height="match_parent"
>
android:id="@+id/bt"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@android:color/black"
android:layout_gravity="bottom"
android:text="点我向上"
android:textColor="#ffffff"
/>
</frameLayout>
布局最外层使用FrameLayout,然后套上ScrollView,但是一定要注意ScrollView的高只能是wrap_content,要不然点击回到底部没效果。
代码如下
public class MainActivity extends AppCompatActivity {
private ScrollView sc;
private WebView wb;
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sc=(ScrollView)findViewById(R.id.sc);
wb=(WebView)findViewById(R.id.wb);
bt=(Button)findViewById(R.id.bt);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sc.post(new Runnable() {
@Override
public void run() {
sc.post(new Runnable() {
public void run() {
// 回到顶部
sc.fullScroll(ScrollView.FOCUS_UP);
}
});
}
});
}
});
initView();
}
private void initView() {
String url = "https://www.111cn.net/";
WebSettings webSettings = wb.getSettings();
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
webSettings.setJavaScriptEnabled(true); //设置WebView属性执行Javascript脚本
//设置可以访问文件
webSettings.setAllowFileAccess(true);
webSettings.setBuiltInZoomControls(false);// 设置是否显示缩放工具
wb.loadUrl(url);
wb.setWebViewClient(new WebViewClient());
}
}
实现效果如图,我这里是使用webView链接百度的网页,换成其他的控件也是一样的