Android ViewPager 中加载 Fragmenet的两种方式
一、当fragment里面的内容较少时,直接 使用fragment xml布局文件填充
文件总数
布局文件:view_one.xml + view_two.xml
自定义Adapter类: MyPagerAdapter1.java (继承自 PagerAdapter 类)
Activity 布局文件: activity_test_vp1.xml
Activity Java文件: MainActivity.java
本文以2个Page为例,来展现实现代码
1)xml布局文件
view_one.xml (view_two.xml类似)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFBA55" android:gravity="center" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="第一个Page" android:textColor="#000000" android:textSize="18sp" android:textStyle="bold" /> </LinearLayout>
2)自定义Adapter类 MyPagerAdapter1.java
package com.jack.testmd;import android.support.v4.view.PagerAdapter;import android.view.View;import android.view.ViewGroup;import java.util.ArrayList;public class MyPagerAdapter1 extends PagerAdapter { private ArrayList<View> viewLists; public MyPagerAdapter1(ArrayList<View> viewLists) { this.viewLists = viewLists; } @Override public int getCount() { return viewLists.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(viewLists.get(position)); return viewLists.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(viewLists.get(position)); }}
3)Activity 布局文件: activity_test_vp1.xml
<?xml version="1.0" encoding="utf-8"?> <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=".TestVp1Activity"> <android.support.v4.view.ViewPager android:id="@+id/vpager_one" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v4.view.ViewPager> </RelativeLayout>
4)使用 -- Activity Java文件: MainActivity.java :
private ViewPager vpager_one; private ArrayList<View> aList; private MyPagerAdapter1 mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_vp1); vpager_one = (ViewPager) findViewById(R.id.vpager_one); //页面数据较少的情况 或 页面很简单 aList = new ArrayList<View>(); aList.add(getLayoutInflater().inflate(R.layout.view_one, null, false)); aList.add(getLayoutInflater().inflate(R.layout.view_two, null, false)); mAdapter = new MyPagerAdapter1(aList); vpager_one.setAdapter(mAdapter); }
方法二:
https://www.cnblogs.com/wukong1688/p/10693536.html
Android ViewPager 中加载 Fragment的两种方式 方式(二)
本博客地址: wukong1688
本文原文地址:https://www.cnblogs.com/wukong1688/p/10692055.html
转载请著名出处!谢谢~~
来源:https://www.cnblogs.com/wukong1688/p/10693338.html