package com.example.usinghorizontalview;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
private LinearLayout mLl;
private HorizontalScrollView mHsv;
//屏幕宽度
private int mScreenWidth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取屏幕宽度
mScreenWidth = getResources().getDisplayMetrics().widthPixels;
initViews();
initEvents();
}
private void initEvents() {
int childCount = mLl.getChildCount();
for (int i = 0; i < childCount; i++) {
final int curIndex = i;
View child = mLl.getChildAt(i);
// 添加点击事件
child.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectTab(curIndex);
}
});
}
}
/**
* 选中索引值为curIndex的tab
* @param curIndex
*/
protected void selectTab(int curIndex) {
int childCount = mLl.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = mLl.getChildAt(i);
//设置选中状态
child.setSelected(i == curIndex);
}
View curTabView = mLl.getChildAt(curIndex);
//获取x的值
int left = curTabView.getLeft();
int width = curTabView.getMeasuredWidth();
int toX = left + width/2 - mScreenWidth/2 ;
//滚动
mHsv.smoothScrollTo(toX, 0);
}
private void initViews() {
mHsv = (HorizontalScrollView) findViewById(R.id.hsv);
mLl = (LinearLayout) findViewById(R.id.ll);
// 默认选中第一个
mLl.getChildAt(0).setSelected(true);
}
}