在 ViewPager android 的中心对齐子视图 [英] Align the child views in center of the ViewPager android

查看:33
本文介绍了在 ViewPager android 的中心对齐子视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将子视图设置为 ViewPager 的中心,并且我想将下一个和上一个视图的某些部分显示到当前视图侧(例如 1 下面的当前屏幕).但目前当前视图从 ViewPager 的左侧开始(如 2 下面的预期屏幕).我怎样才能做到这一点?

这是我的代码..

MyViewPagerAdapter

公共类 MyViewPagerAdapter 扩展 PagerAdapter {私人活动 mActivity;私人 int mPageCount;公共 MyViewPagerAdapter(活动活动,int pageCount){mActivity = 活动;mPageCount = 页数;}@覆盖公共 int getCount() {返回 mPageCount;}@覆盖public boolean isViewFromObject(View view, Object obj) {返回(视图==(视图)obj);}@覆盖public Object instantiateItem(ViewGroup container,final int position) {ViewGroup viewGroup = (ViewGroup)mActivity.getLayoutInflater().inflate(R.layout.item_view,空);viewGroup.setBackgroundColor(randomColor());TextView textView = (TextView)viewGroup.findViewById(R.id.textView1);textView.setText("页面:"+(position+1));按钮按钮 = (Button) viewGroup.findViewById(R.id.button1);button.setOnClickListener(new OnClickListener() {@覆盖公共无效 onClick(查看 v){Toast.makeText(mActivity, "嘿,它被点击了!!!在页面 "+(position+1), Toast.LENGTH_LONG).show();}});容器.addView(viewGroup);返回视图组;}随机 rnd = new Random();私人整数随机颜色(){返回 Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));}@覆盖public void destroyItem(ViewGroup collection, int position, Object view) {//必须被覆盖,否则抛出异常,因为没有被覆盖.Log.d("标签", collection.getChildCount()+"");collection.removeView((View) 视图);}@覆盖公共浮动getPageWidth(int位置){返回 0.8f;}}

MainActivity

公共类 MainActivity 扩展 Activity {私人 ViewPager viewPager;线性布局线性布局;私有整数 ID = 100;私人最终 int 计数 = 8;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);viewPager = (ViewPager) findViewById(R.id.viewPager);linearLayout = (LinearLayout) findViewById(R.id.indicator_layout);生成指标(计数);MyViewPagerAdapter 适配器 = new MyViewPagerAdapter(this, count);viewPager.setAdapter(适配器);viewPager.setOnPageChangeListener(new OnPageChangeListener() {int oldPosition = 0;@覆盖公共无效 onPageSelected(int position) {//这会改变旧位置的视图状态图像((TextView)linearLayout.getChildAt(oldPosition)).setText("");旧位置 = 位置;//这会改变当前位置的视图状态图像((TextView)linearLayout.getChildAt(position)).setText((position+1)+"");}//此方法将被重复调用,直到另一项作为最前面的一项(活动项)@覆盖公共无效 onPageScrolled(int arg0,float arg1,int arg2){}//这将根据滚动状态调用@覆盖公共无效 onPageScrollStateChanged(int arg0){}});viewPager.setOffscreenPageLimit(4);}私人无效生成指标(整数计数){///将 14 dip 转换为其等效的 pxint padd = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, getResources().getDisplayMetrics());for(int i=0;i

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"工具:context=".MainActivity" >(https://github.com/noundla/Sunny_Projects/tree/master/CenterLockViewPager)

您必须将 com.noundla.centerviewpagersample.comps 包中的文件复制到您的项目中.您可以在 MainActivity 类中看到该 Viewpager 的用法.

如果有人对此有问题,请告诉我.

I need to set the child view as center of the ViewPager and also I would like to show some part of the next and previous views to the current view sides(like current screen below 1). But currently the current view is starting at left side of the ViewPager(like expected screen below 2). How can I achieve that?

Here is my code..

MyViewPagerAdapter

public class MyViewPagerAdapter extends PagerAdapter {
    private Activity mActivity;
    private int mPageCount;
    public MyViewPagerAdapter(Activity activity,int pageCount) {
        mActivity = activity;
        mPageCount = pageCount;
    }

    @Override
    public int getCount() {
        return mPageCount;
    }

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        return (view ==(View)obj);
    }

    @Override
    public Object instantiateItem(ViewGroup container,final int position) {
        ViewGroup viewGroup = (ViewGroup)mActivity.getLayoutInflater().inflate(
                R.layout.item_view, null);

        viewGroup.setBackgroundColor(randomColor());

        TextView textView = (TextView)viewGroup.findViewById(R.id.textView1);
        textView.setText("Page: "+(position+1));
        Button button = (Button) viewGroup.findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(mActivity, "Hey, Its clicked!!! at page "+(position+1), Toast.LENGTH_LONG).show();
            }
        });
        container.addView(viewGroup);
        return viewGroup;
    }

    Random rnd = new Random();
    private int randomColor(){
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        //must be overridden else throws exception as not overridden.
        Log.d("Tag", collection.getChildCount()+"");
        collection.removeView((View) view);
    }

    @Override
    public float getPageWidth(int position) {
        return 0.8f;
    }
}

MainActivity

public class MainActivity extends Activity {
    private ViewPager viewPager;
    LinearLayout linearLayout;
    private int ID = 100; 

    private final int count = 8;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        linearLayout  = (LinearLayout) findViewById(R.id.indicator_layout);
        generateIndicators(count);


        MyViewPagerAdapter adapter = new MyViewPagerAdapter(this, count);
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {
            int oldPosition = 0;
            @Override
            public void onPageSelected(int position) {
                //this changes the old position's view state image
                ((TextView)linearLayout.getChildAt(oldPosition)).setText("");
                oldPosition = position;


                //this changes the current position's view state image
                ((TextView)linearLayout.getChildAt(position)).setText((position+1)+"");

            }
            //this method will be called repeatedly upto another item comes as front one(active one)
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {


            }
            //this will be called as per scroll state
            @Override
            public void onPageScrollStateChanged(int arg0) {


            }
        });

        viewPager.setOffscreenPageLimit(4);

    }

    private void generateIndicators(int count) {
        /// Converts 14 dip into its equivalent px
        int padd = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, getResources().getDisplayMetrics());

        for(int i=0;i<count;i++){
            TextView textView = new TextView(this);
            textView.setId(ID+i);
            final int currentItem = i;
            textView.setBackgroundResource(R.drawable.white_cell);
            textView.setPadding(padd,padd,padd,padd);
            /// Converts 14 dip into its equivalent px
            int size = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
            textView.setTextSize(size);
            textView.setGravity(Gravity.CENTER);
            /// Converts 14 dip into its equivalent px
            int px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, getResources().getDisplayMetrics());

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(px, px);
            linearLayout.addView(textView,params);
        }

        ((TextView)linearLayout.getChildAt(0)).setText("1");

    }





}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >



   <android.support.v4.view.ViewPager
       android:id="@+id/viewPager"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:layout_alignParentLeft="true"
       android:layout_alignParentTop="true" >
   </android.support.v4.view.ViewPager>


   <LinearLayout
       android:id="@+id/indicator_layout"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentBottom="true"
       android:layout_centerHorizontal="true"
       android:layout_marginBottom="19dp" >
   </LinearLayout>

</RelativeLayout>

item_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="match_parent"
    android:id="@+id/root_view"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="click me" />

</LinearLayout>

Current screen

expected screen

解决方案

Finally, I have added my solution for this question in GitHub. I have done some pretty tricks to get the workaround solution. You can get the project from the below link(Actually I have planned to create a blog with the explanation , but I dint have that much time to do).

Here is the link(https://github.com/noundla/Sunny_Projects/tree/master/CenterLockViewPager)

You have to copy the files from com.noundla.centerviewpagersample.comps package to your project. And you can see the usage of that Viewpager in MainActivity class.

Please let me know if anyone has problems with this.

这篇关于在 ViewPager android 的中心对齐子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆