带有页面指示器的Android视图翻页器

28

我需要在带有图像的视图页文件中获取页面指示器。以下是我的代码:

public class IndicatorActivity extends Activity {


 /** Called when the activity is first created. */
    @Override

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            MyPagerAdapter adapter = new MyPagerAdapter();
            ViewPager myPager = (ViewPager) findViewById(R.id.pager);
            myPager.setAdapter(adapter);
            myPager.setCurrentItem(0);
            TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicat);
            indicator.setViewPager( myPager );
    }
}
在这段代码中,我在 TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicat); 部分遇到了错误,提示 TitlePageIndicator cannot be resolved to a type。这个错误是什么意思?如何解决呢?
以下是我的xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
         />
    <com.viewpagerindicator.TitlePageIndicator
    android:id="@+id/indicat"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent" />
</LinearLayout>

我需要在 TitlePageIndicator 中编写什么代码? 我想不借助片段实现此功能。

我还创建了一个类,例如:

class MyPagerAdapter extends PagerAdapter {

     private static Integer[] titles = new Integer[] 
                { 
        R.drawable.jk,R.drawable.lm,R.drawable.no
                };

    public int getCount() {
            return 3;
    }

    public Object instantiateItem(View collection, int position) {

            LayoutInflater inflater = (LayoutInflater) collection.getContext()
                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view;
            ImageView iv;

            view = inflater.inflate(R.layout.first, null);

            ((ViewPager) collection).addView(view, 0);
            switch (position) {
            case 0:
                iv = (ImageView)view.findViewById(R.id.imageView1);
                iv.setImageResource(titles[position]);
                    break;
            case 1:
                iv = (ImageView)view.findViewById(R.id.imageView1);
                iv.setImageResource(titles[position]);
                    break;
            case 2:
                 iv = (ImageView)view.findViewById(R.id.imageView1);
                iv.setImageResource(titles[position]);
                    break;
            }
            return view;
    }

    public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView((View) arg2);

    }



    public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == ((View) arg1);

    }

}

这个类我还需要做些什么吗?

先感谢您的帮助。


我只在Eclipse中工作。我已经这样做了,但是它没有被导入到程序中。 - user1602259
有没有其他导入的方式? - user1602259
1
只需在文件的第二行(public class ...之前)键入import com.viewpagerindicator.TitlePageIndicator。只要正确设置库,它就能工作。 - Aleks G
有没有其他的方法将它导入到我的类中? - user1602259
不需要第三方代码或任何手动操作。TabLayout是构建页面指示器的完美小部件。请查看此答案:https://stackoverflow.com/a/44231881/1850606 - xleon
显示剩余2条评论
7个回答

54

更新: 2017年3月22日

主要片段布局:

       <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v4.view.ViewPager
                android:id="@+id/viewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <RadioGroup
                android:id="@+id/page_group"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal|bottom"
                android:layout_marginBottom="@dimen/margin_help_container"
                android:orientation="horizontal">

                <RadioButton
                    android:id="@+id/page1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="true" />

                <RadioButton
                    android:id="@+id/page2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <RadioButton
                    android:id="@+id/page3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </RadioGroup>
        </FrameLayout>

在您的片段中设置视图和事件,可以像这样:

        mViewPaper = (ViewPager) view.findViewById(R.id.viewpager);
        mViewPaper.setAdapter(adapder);

        mPageGroup = (RadioGroup) view.findViewById(R.id.page_group);
        mPageGroup.setOnCheckedChangeListener(this);

        mViewPaper.addOnPageChangeListener(this);

       *************************************************
       *************************************************

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        // when current page change -> update radio button state
        int radioButtonId = mPageGroup.getChildAt(position).getId();
        mPageGroup.check(radioButtonId);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        // when checked radio button -> update current page
        RadioButton checkedRadioButton = (RadioButton)radioGroup.findViewById(checkedId);
        // get index of checked radio button
        int index = radioGroup.indexOfChild(checkedRadioButton);

        // update current page
        mViewPaper.setCurrentItem(index), true);
    }

自定义复选框状态:自定义复选框图片Android

Viewpager教程:http://architects.dzone.com/articles/android-tutorial-using

输入图像描述


1
不错的解决方案,不需要外部库!我只是使用一个简单的自定义视图来显示点而不是圆点扩展了这个想法。非常感谢! - j.c
1
@j.c 你能帮我制作一个自定义单选按钮吗? 我尝试过只更改背景,但点和轮廓仍然始终在其上方。 - pblead26
2
setOnPageChangeListener已被弃用,请使用addOnPageChangeListener代替。 - Bjørn Stenfeldt

12

以下是需要执行的几个步骤:

1- 如果您还没有下载库,请下载

2-导入到Eclipse中。

3-将项目设置为使用该库: Project->属性->Android->向下滚动至“Library”部分,点击Add...并选择viewpagerindicator。

4-现在您应该能够导入 com.viewpagerindicator.TitlePageIndicator了。

现在关于如何实现不使用fragment:

在附带viewpagerindicatior的示例中,您可以看到库与具有FragmentPagerAdapterViewPager一起使用。

但实际上,该库本身与Fragment无关。它只需要一个ViewPager。 因此,只需使用PagerAdapter而不是FragmentPagerAdapter,就可以轻松完成。


我使用了PageAdapter创建了一个类。请检查我的程序。我已经更新了它...现在请帮帮我... - user1602259
1
我按照您的指示设置了库。但是在项目->属性->Android->向下滚动到库部分,点击添加...中没有viewpagerindicator。 - user1602259
我是否想要创建一个名为TitlePageIndicator或其他任何类的类? - user1602259
嘿,Benito,我正在为三个选项卡使用相同的库,每个选项卡都有一个带有相同ArrayList的ListView设置到它们的适配器中。如果我在这三个选项卡中的任何一个列表中勾选复选框(我正在更新数据库和我的列表),其他两个应该反映出更改,请在此方面给我帮助。你可以在这里找到我的问题: https://dev59.com/dWjWa4cB1Zd3GeqPoCxf - skygeek

10
我知道这个问题已经有答案了,但是对于任何想要简单、没有花哨实现的ViewPager指示器的人,我已经实现了一个并且开源了。如果发现Jake Wharton的版本有点复杂,可以看看这个:https://github.com/jarrodrobins/SimpleViewPagerIndicator。请注意,保留了HTML标签。

2
@JRod,我试用了你的库,但是当我尝试滑动视图时,在setCurrentItem()方法中的ImageView item = items.get(i);这一行代码导致我的应用程序崩溃。 - irobotxx

5
我也使用过@JROD的SimpleViewPagerIndicator组件。正如@manuelJ所描述,它也会崩溃。
根据他的文档:
SimpleViewPagerIndicator pageIndicator = (SimpleViewPagerIndicator) findViewById(R.id.page_indicator);
pageIndicator.setViewPager(pager);

请确保您也添加了这一行:
pageIndicator.notifyDataSetChanged();

由于SimpleViewPagerIndicator未能正确实例化并且items为空,因此它会崩溃并出现数组越界异常。调用notifyDataSetChanged会导致所有值被正确设置或重置。


2

以下是对@vuhung3990提供的好答案的改进。

我已经实现了这个解决方案,它运行得非常好,但是如果我触摸一个单选按钮,它会被选中,但什么也不会发生。

建议在点击单选按钮时也更改页面。要做到这一点,只需向单选组添加一个监听器:

mPager = (ViewPager) findViewById(R.id.pager);
final RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radiogroup);    
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radioButton :
                        mPager.setCurrentItem(0, true);
                        break;
                    case R.id.radioButton2 :
                        mPager.setCurrentItem(1, true);
                        break;
                    case R.id.radioButton3 :
                        mPager.setCurrentItem(2, true);
                        break;
                }
            }
        });

谢谢,我会更新我的答案,但会有一些不同。 - vuhung3990

1

您需要执行以下操作:

1-从这里下载完整项目https://github.com/JakeWharton/ViewPagerIndicator ViewPager Indicator

2-将其导入Eclipse。

导入后,如果您想创建以下类型的屏幕,请按照以下步骤操作 -

Screen Shot

变更于

示例圆形默认值

  package com.viewpagerindicator.sample;
  import android.os.Bundle;  
  import android.support.v4.view.ViewPager;
  import com.viewpagerindicator.CirclePageIndicator;

  public class SampleCirclesDefault extends BaseSampleActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_circles);

    mAdapter = new TestFragmentAdapter(getSupportFragmentManager());

    mPager = (ViewPager)findViewById(R.id.pager);
  //  mPager.setAdapter(mAdapter);

    ImageAdapter adapter = new ImageAdapter(SampleCirclesDefault.this);
    mPager.setAdapter(adapter);


    mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
    mIndicator.setViewPager(mPager);
  }
}

ImageAdapter 图像适配器
 package com.viewpagerindicator.sample;

 import android.content.Context;
 import android.support.v4.view.PagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ImageView;
 import android.widget.TextView;

 public class ImageAdapter extends PagerAdapter {
 private Context mContext;

 private Integer[] mImageIds = { R.drawable.about1, R.drawable.about2,
        R.drawable.about3, R.drawable.about4, R.drawable.about5,
        R.drawable.about6, R.drawable.about7

 };

 public ImageAdapter(Context context) {
    mContext = context;
 }

 public int getCount() {
    return mImageIds.length;
 }

 public Object getItem(int position) {
    return position;
 }

 public long getItemId(int position) {
    return position;
 }

 @Override
 public Object instantiateItem(ViewGroup container, final int position) {

    LayoutInflater inflater = (LayoutInflater) container.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View convertView = inflater.inflate(R.layout.gallery_view, null);

    ImageView view_image = (ImageView) convertView
            .findViewById(R.id.view_image);
    TextView description = (TextView) convertView
            .findViewById(R.id.description);

    view_image.setImageResource(mImageIds[position]);
    view_image.setScaleType(ImageView.ScaleType.FIT_XY);

    description.setText("The natural habitat of the Niligiri tahr,Rajamala          Rajamala is 2695 Mts above sea level"
        + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
                    + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level");

    ((ViewPager) container).addView(convertView, 0);

    return convertView;
 }

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

 @Override
 public void destroyItem(ViewGroup container, int position, Object object) {
    ((ViewPager) container).removeView((ViewGroup) object);
 }
}

gallery_view.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/about_bg"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/about_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <LinearLayout
        android:id="@+id/about_layout1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".4"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/view_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent" 
            android:background="@drawable/about1">
     </ImageView>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/about_layout2"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".6"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SIGNATURE LANDMARK OF MALAYSIA-SINGAPORE CAUSEWAY"
            android:textColor="#000000"
            android:gravity="center"
            android:padding="18dp"
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearance" />


        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:fillViewport="false"
            android:orientation="vertical"
            android:scrollbars="none"
            android:layout_marginBottom="10dp"
            android:padding="10dp" >

            <TextView
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="#000000"
                android:text="TextView" />

            </ScrollView>
    </LinearLayout>
 </LinearLayout>


1

您可以创建一个包含TextView数组(mDots)的线性布局。 为了将textView表示为点,请在您的代码中提供此HTML源代码。 参考我的代码。 我从Youtube频道TVAC Studio获取了这些信息。 这是代码:

    addDotsIndicator(0);
    viewPager.addOnPageChangeListener(viewListener);
}

public void addDotsIndicator(int position)
{
        mDots = new TextView[5];
        mDotLayout.removeAllViews();

        for (int i = 0; i<mDots.length ; i++)
        {
             mDots[i]=new TextView(this);
             mDots[i].setText(Html.fromHtml("&#8226;"));            //HTML for dots
             mDots[i].setTextSize(35);
             mDots[i].setTextColor(getResources().getColor(R.color.colorAccent));

             mDotLayout.addView(mDots[i]);
        }

        if(mDots.length>0)
        {
            mDots[position].setTextColor(getResources().getColor(R.color.orange));
        }
}

ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int 
   positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        addDotsIndicator(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
};`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接