在使用HorizontalScrollView我們常常需要讓點擊的view自動居中,可以用smoothScrollTo(x,y)
或者scrollTo(x,y)
來實現
這兩個方法效果是一樣的,只不過smoothScrollTo(x,y)
是平滑移動,scrollTo(x,y)
是直接跳過去
需要注意的是這兩個方法是相對於HorizontalScrollView控件的左邊緣(如果是豎向則是上邊緣)進行偏移的,x是左邊緣向右偏移的距離,y是上邊緣向下偏移的距離,本博客僅示範橫向偏移,豎向偏移同理。
以下是HorizontalScrollView 的示例,關鍵代碼在getCenterItem()方法裏
Android HorizontalScroll 自動居中
<!--這個是在屏幕中畫一條豎向中線,用於指示位置-->
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:background="#000000" />
<HorizontalScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="150dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:scrollbars="none"
android:requiresFadingEdge="horizontal"
android:fadingEdgeLength="0dp">
<LinearLayout
android:id="@+id/horizontalScrollViewItemContainer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
// 初始化佈局中的控件
private HorizontalScrollView horizontalScrollView = view.findViewById(R.id.horizontalScrollView);
private LinearLayout linearLayout = view.findViewById(R.id.horizontalScrollViewItemContainer);
// item的值
private String[] names = new String[]{"劉一", "鄭二", "張三", "李四", "王五", "趙六"};
private ArrayList<String> data = new ArrayList<>();
// 將集合中的數據綁定到HorizontalScrollView上
private void bindData(View view) {
// 爲佈局中textview設置好相關屬性
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
layoutParams.setMargins(20, 10, 20, 10);
// 將字符串數組與集合綁定起來
Collections.addAll(data, names);
for (int i = 0; i < data.size(); i++){
TextView textView = new TextView(getActivity());
textView.setText(data.get(i));
textView.setTextColor(Color.WHITE);
textView.setLayoutParams(layoutParams);
textView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
// 手指離開後使當前Item居中
if (event.getAction() == MotionEvent.ACTION_UP) {
// 使Item居中
getCenterItem(view);
}
return true;
}
});
linearLayout.addView(textView);
linearLayout.invalidate();
}
}
private void getCenterItem(View view) {
// 獲取horizontalScrollView的寬度
int hsvWidth = horizontalScrollView.getWidth();
// 獲取textview左邊緣的位置
int textViewLeft = view.getLeft();
// 獲取textview Item的寬度
int textViewWidth = view.getWidth();
// 計算偏移量
int offset = textViewLeft + textViewWidth / 2 - hsvWidth / 2;
// 橫向平滑滾動偏移
horizontalScrollView.smoothScrollTo(offset, 0);
// 得到當前居中的Item名字
String s = "CenterLocked Item: "+((TextView)view).getText();
Log.v("performItemClick", s);
}