android - 从屏幕中心开始和结束水平滚动视图
问题描述
我需要在水平滚动视图中开始和结束内容,就像我们在画廊(不推荐使用)小部件中一样。Horizontal scrollview 内的内容应该从屏幕中心开始,滚动时应该从中心向左移动,与 Gallery 相同。
我有几百张图像,动态填充在水平滚动视图内的线性布局中。我实现了以一秒的时间延迟自动滚动水平滚动视图。但我需要从中心开始内容并以中心结束。
public class ImageGalleryScrollActivity
extends AppCompatActivity {
HorizontalScrollView horizontalScrollView;
int maxCount=59;
Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
horizontalScrollView.smoothScrollBy(maxCount, 0);
mHandler.sendMessageDelayed(new Message(), 1000);
return false;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.horizontal_scroll_activity);
horizontalScrollView=(HorizontalScrollView)findViewById(R.id.horizontalView);
mHandler.sendMessageDelayed(new Message(), 1000);
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<HorizontalScrollView
android:id="@+id/horizontalView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:fillViewport="true">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
解决方案
您可以将每个等于屏幕宽度一半的左/右填充与android:clipToPadding="false"
滚动视图上的属性结合起来。
由于在运行时之前您不会知道需要多少填充,因此您必须在 Java 中设置填充。把它放在你的onCreate()
:
scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int padding = getResources().getDisplayMetrics().widthPixels / 2;
scrollView.setPadding(padding, 0, padding, 0);
scrollView.setClipToPadding(false);
}
});
推荐阅读
- javascript - 在Javascript中,如何将1个变量生成的数字组合成一个数组
- python - 在 django 中调用回调 URL 时出现 Forbidden (403) 错误
- xamarin.forms - 在 google play 上发布 xamarin 应用程序的问题
- sql - 在 Pivot 块中获取无效标识符 ORA-00904
- javascript - 命令处理程序丰富的嵌入类型错误:无法读取未定义的属性“发送”
- google-apps-script - 将公式添加到列中的空白单元格
- python - 如何在 Python 中读取多行输入?
- recursion - Clojure:你能在递归函数中连接吗?
- constructor - NewFeedModel 的构造函数不能应用于给定类型
- r - 如何找到低于0值的5行或更多行(日期)系列的第一行(日期)