重写HorizontalScrollView实现代码控制水平滚动定位
CenterShowHorizontalScrollView.java
package com.aldx.hccraftsman.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import com.aldx.hccraftsman.R;
import com.aldx.hccraftsman.utils.Utils;
/**
* author: chenzheng
* created on: 2017/5/10 16:26
* description:
*/
public class CenterShowHorizontalScrollView extends HorizontalScrollView {
private LinearLayout mShowLinear;
private Context context;
public CenterShowHorizontalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
mShowLinear = new LinearLayout(context);
mShowLinear.setOrientation(LinearLayout.HORIZONTAL);
HorizontalScrollView.LayoutParams params = new HorizontalScrollView.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
mShowLinear.setGravity(Gravity.CENTER_VERTICAL);
this.addView(mShowLinear, params);
}
public void onClicked(View v) {
if (v.getTag(R.id.item_position) != null) {
int position = (Integer) v.getTag(R.id.item_position);
View itemView = mShowLinear.getChildAt(position);
int itemWidth = itemView.getWidth();
int screenWidth = Utils.getScreenW(context);
smoothScrollTo(itemView.getLeft() - (screenWidth / 2 - itemWidth / 2), 0);
}
}
public void onClicked(int position) {
View itemView = mShowLinear.getChildAt(position);
int itemWidth = itemView.getWidth();
int screenWidth = Utils.getScreenW(context);
smoothScrollTo(itemView.getLeft() - (screenWidth / 2 - itemWidth / 2), 0);
}
public LinearLayout getLinear() {
return mShowLinear;
}
public void addItemView(View itemView, int position) {
itemView.setTag(R.id.item_position, position);
mShowLinear.addView(itemView);
}
}
<com.aldx.hccraftsman.view.CenterShowHorizontalScrollView
android:id="@+id/tab_horizontalscrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#e5e5e5"
android:scrollbars="none" />
CenterShowHorizontalScrollView内部已经添加过LinearLayout所以不需要再重复添加了,直接将子view添加进去即可:
mHScrollView.addItemView(itemView, i);
代码控制滚动定位:
mHScrollView.onClicked(view);
或
mHScrollView.onClicked(position);
注:
如果你再oncreate方法里就想调用滚动定位,是看不到效果的,因为这时控件的宽度还没有被测量出来,解决方法:
mHScrollView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if(tempViewList.size()>0) {
mHScrollView.onClicked(temp_tab);
}
mHScrollView.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
});