android这样的效果怎么实现的,上边是3张图片 10
推荐于2016-03-30 · 知道合伙人软件行家
这是android中的viewPager中常用的一种效果
例如APP首次启动的欢迎界面,通常都会带几个这种小点,用于告诉用户,当前是第几个界面
实效果如下:
android.support.v4.ViewPager类在 API 4+ Support 支持包中开始为我们提供,它可以让我们有能力左右滑动以'页'的形式展示数据。我们可以通过继承 PagerAdapter 来生成页面形式的视图。介绍具体的使用方式之前先来看下效果
2.实现代码:
首先需要在layout文件中配置ViewPager View
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp" />
3.Activity的实现代码
public class MainActivity extends Activity {
ArrayList<View> mViewList = new ArrayList<View>();
LayoutInflater mLayoutInflater;
LinearLayout mNumLayout;
Button mPreSelectedBt;
MyPagerAdapter mPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLayoutInflater = getLayoutInflater();
//可以按照需求进行动态创建Layout,这里暂用静态的xml layout
mViewList.add(mLayoutInflater.inflate(R.layout.per_pager1, null));
mViewList.add(mLayoutInflater.inflate(R.layout.per_pager2, null));
mViewList.add(mLayoutInflater.inflate(R.layout.per_pager3, null));
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new MyPagerAdapter();
viewPager.setAdapter(mPagerAdapter);
mNumLayout = (LinearLayout) findViewById(R.id.ll_pager_num);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_dot_normal);
for (int i = 0; i < mViewList.size(); i++) {
Button bt = new Button(this);
bt.setLayoutParams(new ViewGroup.LayoutParams(bitmap.getWidth(),bitmap.getHeight()));
bt.setBackgroundResource(R.drawable.icon_dot_normal);
mNumLayout.addView(bt);
}
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
if(mPreSelectedBt != null){
mPreSelectedBt.setBackgroundResource(R.drawable.icon_dot_normal);
}
Button currentBt = (Button)mNumLayout.getChildAt(position);
currentBt.setBackgroundResource(R.drawable.home_page_dot_select);
mPreSelectedBt = currentBt;
//Log.i("INFO", "current item:"+position);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
class MyPagerAdapter extends PagerAdapter{
@Override
public int getCount() {
return mViewList.size();
}
@Override
public Object instantiateItem(View container, int position) {
Log.i("INFO", "instantiate item:"+position);
((ViewPager) container).addView(mViewList.get(position),0);
return mViewList.get(position);
}
@Override
public void destroyItem(View container, int position, Object object) {
Log.i("INFO", "destroy item:"+position);
((ViewPager) container).removeView(mViewList.get(position));
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
}
有关viewPager + Adapter的更多用法,建议查看使用教程
2014-03-31