viewpage 添加fragment 报错
、
上面引入的Fragment 不对,导致报错
更换Fragment的依赖适应v4 或者androdx
viewpage demo
主要:main 的 layout 加viewpage ,新建fragment 加载fragment view;设定fragmentadpter.在main中使用viewpage设置adapter;
注意:在新建fragment的时候一定之一引入的fragment 的包。细心啊;
main:
package cuiweiyou.headerrecycleview; import android.os.Bundle; import android.widget.LinearLayout; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.viewpager.widget.ViewPager; import java.util.ArrayList; import java.util.List; import cuiweiyou.headerrecycleview.adapter.FragmentAdapter; import cuiweiyou.headerrecycleview.adapter.HeaderRcyvAdapter; import cuiweiyou.headerrecycleview.bean.HeaderBean; import cuiweiyou.headerrecycleview.bean.NormalBean; import cuiweiyou.headerrecycleview.fragment.FragmentOne; /** * www.gaohaiyan.com */ public class MainActivityViewpage extends AppCompatActivity { private List<NormalBean> mNormalList = new ArrayList<NormalBean>(); // 普通item的数据集 private HeaderBean mHeaderBean; // header的数据 private LinearLayout activityMain; private ViewPager vp; private List<Fragment> fragmentList = new ArrayList<>(); private HeaderRcyvAdapter mHeaderRcyvAdapter; private FragmentAdapter fragmentAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_viewpage); vp = (ViewPager) findViewById(R.id.vp); FragmentOne fragment1 = new FragmentOne(MainActivityViewpage.this,"1"); FragmentOne fragment2 = new FragmentOne(MainActivityViewpage.this,"12"); FragmentOne fragment3 = new FragmentOne(MainActivityViewpage.this,"123"); fragmentList.add(fragment1); fragmentList.add(fragment2); fragmentList.add(fragment3); fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragmentList, "1"); vp.setAdapter(fragmentAdapter); } }
fragment:
package cuiweiyou.headerrecycleview.fragment; import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import cuiweiyou.headerrecycleview.R; @SuppressLint("ValidFragment") public class FragmentOne extends Fragment { private Context mContext; TextView tvHead ; String head; public FragmentOne(Context context,String s) { super(); mContext=context; head=s; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.fragment_one,null); tvHead = (TextView) view.findViewById(R.id.tv_head); tvHead.setText(head); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Nullable @Override public View getView() { return super.getView(); } }
adapter:
package cuiweiyou.headerrecycleview.adapter; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import java.util.ArrayList; import java.util.List; public class FragmentAdapter extends FragmentPagerAdapter { private String tv_title; List<Fragment> mfragmentList=new ArrayList<>(); public FragmentAdapter(FragmentManager fm, List<Fragment> fragmentList, String title) { super(fm); mfragmentList=fragmentList; tv_title = title; } @Override public Fragment getItem(int position) { return mfragmentList.get(position); } @Override public int getCount() { return mfragmentList.size(); } }
LayoutInflater
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tes="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/logo" android:text="张继群" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_bias="0.497" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.425" /> </LinearLayout>
下面主要就是加载LayoutInflater,设定layout,加载layout;
LayoutInflater layoutInfla=LayoutInflater.from(this); View view=layoutInfla.inflate(R.layout.ceshi,null); ll_ceshi.addView(view);
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); RelativeLayout rly = new RelativeLayout(this); Button btnOne = new Button(this); btnOne.setText("按钮1"); Button btnTwo = new Button(this); btnTwo.setText("按钮2"); // 为按钮1设置一个id值 btnOne.setId(123); // 设置按钮1的位置,在父容器中居中 RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); rlp1.addRule(RelativeLayout.CENTER_IN_PARENT); // 设置按钮2的位置,在按钮1的下方,并且对齐父容器右面 RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); rlp2.addRule(RelativeLayout.BELOW, 123); rlp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); // 将组件添加到外部容器中 rly.addView(btnTwo, rlp2); rly.addView(btnOne, rlp1); // 设置当前视图加载的View即rly setContentView(rly); } }
自定义控件轮播图demo
1.获取网络地址的轮播图片。
public class BannerImg extends FrameLayout { private final static boolean isAutoPlay = true; private List<String> imageUris; private List<ImageView> imageViewsList; private List<ImageView> dotViewsList; private LinearLayout mLinearLayout; private ViewPager mViewPager; private int currentItem = 0; private ScheduledExecutorService scheduledExecutorService; @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); mViewPager.setCurrentItem(currentItem); } }; //使用ImageLoader加载网络图片 ImageLoader imageLoader = ImageLoader.getInstance(); DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageForEmptyUri(R.mipmap.pic_one) .showImageOnFail(R.mipmap.pic_two) .showImageOnLoading(R.mipmap.pic_three) .resetViewBeforeLoading(true) .cacheOnDisk(true) .imageScaleType(ImageScaleType.EXACTLY) .bitmapConfig(Bitmap.Config.RGB_565) .considerExifParams(true) .displayer(new FadeInBitmapDisplayer(300)).build(); public BannerImg(Context context) { this(context, null); } public BannerImg(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BannerImg(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub initUI(context); if (!(imageUris.size() <= 0)) { setImageUris(imageUris); } if (isAutoPlay) { startPlay(); } } private void initUI(Context context) { imageViewsList = new ArrayList<ImageView>(); dotViewsList = new ArrayList<ImageView>(); imageUris = new ArrayList<String>(); LayoutInflater.from(context).inflate(R.layout.bannerimg, this, true); mLinearLayout = (LinearLayout) findViewById(R.id.dotsImg); mViewPager = (ViewPager) findViewById(R.id.imagePager); ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context); config.threadPriority(Thread.NORM_PRIORITY - 2); config.denyCacheImageMultipleSizesInMemory(); config.diskCacheFileNameGenerator(new Md5FileNameGenerator()); config.diskCacheSize(50 * 1024 * 1024); // 50 MiB config.tasksProcessingOrder(QueueProcessingType.LIFO); config.writeDebugLogs(); // Remove for release app // Initialize ImageLoader with configuration. imageLoader.init(config.build()); } public void setImageUris(List<String> imageuris) { for (int i = 0; i < imageuris.size(); i++) { imageUris.add(imageuris.get(i)); } for (int i = 0; i < imageUris.size(); i++) { ImageView imageView = new ImageView(getContext()); imageView.setScaleType(ImageView.ScaleType.FIT_XY);//铺满屏幕 imageLoader.displayImage(imageUris.get(i), imageView, options, new SimpleImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { } }); imageViewsList.add(imageView); ImageView viewDot = new ImageView(getContext()); if (i == 0) { viewDot.setBackgroundResource(R.mipmap.dot_focus); } else { viewDot.setBackgroundResource(R.mipmap.dot); } dotViewsList.add(viewDot); mLinearLayout.addView(viewDot); } mViewPager.setFocusable(true); mViewPager.setAdapter(new MyPagerAdapter()); mViewPager.setOnPageChangeListener(new MyPageChangeListener()); } private void startPlay() { scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.scheduleAtFixedRate(new BannerTask(), 1, 4, TimeUnit.SECONDS); } @SuppressWarnings("unused") private void stopPlay() { scheduledExecutorService.shutdown(); } /** * 设置选中的圆点的背景 * * @param selectItems */ private void setImageBackground(int selectItems) { for (int i = 0; i < dotViewsList.size(); i++) { if (i == selectItems) { dotViewsList.get(i).setBackgroundResource(R.mipmap.dot_focus); } else { dotViewsList.get(i).setBackgroundResource(R.mipmap.dot); } } } private class MyPagerAdapter extends PagerAdapter { @Override public void destroyItem(View container, int position, Object object) { // TODO Auto-generated method stub //((ViewPag.er)container).removeView((View)object); ((ViewPager) container).removeView(imageViewsList.get(position)); } @Override public Object instantiateItem(View container, int position) { // TODO Auto-generated method stub ((ViewPager) container).addView(imageViewsList.get(position)); return imageViewsList.get(position); } @Override public int getCount() { // TODO Auto-generated method stub return imageViewsList.size(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return arg0 == arg1; } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { // TODO Auto-generated method stub } @Override public Parcelable saveState() { // TODO Auto-generated method stub return null; } } private class MyPageChangeListener implements ViewPager.OnPageChangeListener { boolean isAutoPlay = false; @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub switch (arg0) { case 1: isAutoPlay = false; break; case 2: isAutoPlay = true; break; case 0: // <span style="font-family: Arial, Helvetica, sans-serif;"> //如果滑到最后,就从头开始</span> //[java] view plain copy if (mViewPager.getCurrentItem() == mViewPager.getAdapter().getCount() - 1 && !isAutoPlay) { mViewPager.setCurrentItem(0); } //如果滑到头就从尾开始 else if (mViewPager.getCurrentItem() == 0 && !isAutoPlay) { mViewPager.setCurrentItem(mViewPager.getAdapter().getCount() - 1); } break; } } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageSelected(int pos) { // TODO Auto-generated method stub setImageBackground(pos); } } private class BannerTask implements Runnable { @Override public void run() { // TODO Auto-generated method stub synchronized (mViewPager) { currentItem = (currentItem + 1) % imageViewsList.size(); handler.obtainMessage().sendToTarget(); } } } }
上面这是一个好用的类,实现轮播图,不过这是加载网络上的图片,不能加载本地的,下面我会提供一个本地加载的。
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v4.view.ViewPager android:id="@+id/imagePager" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/dotsImg" android:gravity="center_horizontal" android:layout_gravity="bottom|center_horizontal"> </LinearLayout> </FrameLayout>
这是布局文件。
<LinearLayout 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" android:orientation="vertical" android:background="@color/balack_thin" android:paddingBottom="10dp"> <com.imobi.callblocker.util.BannerImg android:layout_width="match_parent" android:layout_height="200dp" android:id="@+id/mainBanner"></com.test.controls.BannerImg> </LinearLayout>
上面是具体的应用。
@Override public void onCreated(@Nullable Bundle savedInstanceState) { BannerImg bannerImg=(BannerImg)findViewById(R.id.mainBanner); List<String> imgs=new ArrayList<String>(); imgs.add(0,"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1529508272189&di=0ddf122b1e41f10164d41553cafba0e9&imgtype=0&src=http%3A%2F%2Fimg.duoziwang.com%2F2016%2F12%2F18%2F015634128329.jpg"); imgs.add(1,"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1529508291437&di=8232c28ca25526c2b57d8ac797cd62b9&imgtype=jpg&src=http%3A%2F%2Fimg2.imgtn.bdimg.com%2Fit%2Fu%3D2002181187%2C439438033%26fm%3D214%26gp%3D0.jpg"); bannerImg.setImageUris(imgs);
上面是在你的具体用大的地方去输入你的资源文件。这个只能用于网络加载图片,具体是使用ImageLoder去解析网络地址。
具体如下:
DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageForEmptyUri(R.mipmap.pic_one) .showImageOnFail(R.mipmap.pic_two) .showImageOnLoading(R.mipmap.pic_three) .resetViewBeforeLoading(true) .cacheOnDisk(true) .imageScaleType(ImageScaleType.EXACTLY) .bitmapConfig(Bitmap.Config.RGB_565) .considerExifParams(true) .displayer(new FadeInBitmapDisplayer(300)).build();
我相信你跟家具名字就能知道其中的意思。当url为空的时候,当loadfail的是时候等等。
2.接下来第二只用方法了:相当于自己写一个viewpage,用handle耗时去自动的滑动图片。
既可以加载本地图片的。
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="12dp" android:foregroundGravity="center" android:gravity="center" android:orientation="vertical"> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10dp" /> <LinearLayout android:id="@+id/viewGroup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center_horizontal|bottom" android:orientation="horizontal"> </LinearLayout> </RelativeLayot>
上面是具体的布局文件,接下来是具体的代码了,在相应的java文中。
@Override public void onCreated(@Nullable Bundle savedInstanceState) { initView(); } private void initView() { mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent =new Intent(UnHookCallActivity.this, MainShowActivity.class); startActivity(intent); } }); ViewGroup group = (ViewGroup) findViewById(R.id.viewGroup); vPager = (ViewPager) findViewById(R.id.viewPager); dots = new ImageView[img.length]; for (int i = 0; i < dots.length; i++) { ImageView imageView = new ImageView(this); imageView.setLayoutParams(new WindowManager.LayoutParams(10, 10)); dots[i] = imageView; if (i == 0) { dots[i].setBackgroundResource(R.mipmap.dot_focus); } else { dots[i].setBackgroundResource(R.mipmap.dot); } group.addView(imageView); } //将图片填充到数组中 imageViews = new ImageView[img.length]; for(int i=0; i<imageViews.length; i++){ ImageView imageView = new ImageView(this); imageViews[i] = imageView; imageView.setBackgroundResource(img[i]); } //设置Adapter vPager.setAdapter(new MyPagerAdapter(imageViews)); //设置监听,主要是设置点点的背景 vPager.setOnPageChangeListener(this); //设置ViewPager的默认项, 设置为长度的100倍,这样子开始就能往左滑动 vPager.setCurrentItem((imageViews.length) * 100); handler = new Handler(); handler.postDelayed(new TimerRunnable(),1000); } class TimerRunnable implements Runnable{ @Override public void run() { int curItem = vPager.getCurrentItem(); vPager.setCurrentItem(curItem+1); if (handler!=null){ handler.postDelayed(this,1000); } } }
还会用到:
private void setImageBackground(int index) { for(int i=0; i<dots.length; i++){ if(i == index){ dots[i].setBackgroundResource(R.mipmap.dot_focus); }else{ dots[i].setBackgroundResource(R.mipmap.dot); } } }
在oncreate中调用initView();就行了。
public class MyPagerAdapter extends PagerAdapter { private ImageView[] imageViews;// 轮播图的数组 public MyPagerAdapter(ImageView[] imageViews){ this.imageViews = imageViews; } @Override public int getCount() { return Integer.MAX_VALUE; } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public void destroyItem(View container, int position, Object object) { // ((ViewPager)container).removeView(imageViews[position % imageViews.length]); } /** * 载入图片进去,用当前的position 除以 图片数组长度取余数是关键 */ @Override public Object instantiateItem(View container, int position) { try { ((ViewPager)container).addView(imageViews[position % imageViews.length], 0); }catch(Exception e){ //handler something } return imageViews[position % imageViews.length]; } }
这里是viewpage的adapter。
private ViewPager vPager; private ImageView[] dots; // 小圆点的数组 private ImageView[] imageViews;// 轮播图的数组 private int[] img = new int[] { R.mipmap.pic_one, R.mipmap.pic_two, R.mipmap.pic_three, R.mipmap.pic_one };// 图片 资源
上面的是有关 变量。
这就是第二种方法。