文章目录
- 1.下拉列表Spinner
- 1.数组适配器ArrayAdapter
- 2.简单适配器SimpleAdapter
- 3.基本适配器BaseAdapter
- 2.列表视图ListView
- 3.网格视图GridView
- 4.翻页视图ViewPager
- 5.翻页标签栏pagerTabStrip
- 6.ViewPager实现引导页
- 7.碎片Fragment
- 1.Fragment静态注册
- 2.Fragment生命周期
- 3.Fragment动态注册
1.下拉列表Spinner
1.数组适配器ArrayAdapter
最简单的适配器,只展示一行文字。
- 编写列表项的XML文件,内部布局只有一个TextView标签。
- 调用ArrayAdapter的构造方法,填入待展现的字符串数组,以及列表项的XML文件。
- 调用下拉框控件的setAdapter方法,传入第二部得到的适配器实例。
public class SpinnerDropdownActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {private final static String[] startArray = {"水星","金星","地球","火星","木星"};private Spinner sp_dropdown;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_spinner_dropdown);sp_dropdown = findViewById(R.id.sp_dropdown);// 声明一个下拉列表的数组适配器ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item_select, startArray);sp_dropdown.setAdapter(adapter);// 默认选择第一个sp_dropdown.setSelection(0);sp_dropdown.setOnItemSelectedListener(this);}@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position, long id) {ToastUtil.show(this, "选中了:" + startArray[position]);}@Overridepublic void onNothingSelected(AdapterView<?> parent) {}
}
2.简单适配器SimpleAdapter
SimpleAdapter允许在列表项中同时展示文本和图片。
public class SpinnerIconActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {private static final int[] iconArray = {R.drawable.ikun,R.drawable.ikun,R.drawable.ikun,R.drawable.ikun,R.drawable.ikun};private static final String[] iconTextArray = {"IKUN1","IKUN2","IKUN3","IKUN4","IKUN5"};private Spinner sp_icon;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_spinner_icon);sp_icon = findViewById(R.id.sp_icon);List<Map<String,Object>> list = new ArrayList<>();for(int i=0;i< iconArray.length;i++){Map<String,Object> item = new HashMap<>();item.put("icon", iconArray[i]);item.put("name", iconTextArray[i]);list.add(item);}SimpleAdapter adapter = new SimpleAdapter(this, list,R.layout.item_simple,new String[]{"icon","name"},new int[]{R.id.iv_icon,R.id.tv_name});sp_icon.setAdapter(adapter);sp_icon.setSelection(0);sp_icon.setOnItemSelectedListener(this);}@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position, long id) {ToastUtil.show(this,"选中了:" + iconTextArray[position]);}@Overridepublic void onNothingSelected(AdapterView<?> parent) {}
}
3.基本适配器BaseAdapter
BaseAdapter是一种适应性更强的基本适配器。
public class CustomBaseAdapter extends BaseAdapter {private Context mContext;private List<Planet> mPlanets;public CustomBaseAdapter(Context context, List<Planet> planets) {mContext = context;mPlanets = planets;}@Overridepublic int getCount() {return mPlanets.size();}@Overridepublic Object getItem(int position) {return mPlanets.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {View view = LayoutInflater.from(mContext).inflate(R.layout.item_list, null);ImageView iv_icon = view.findViewById(R.id.iv_icon);TextView tv_name = view.findViewById(R.id.tv_name);TextView tv_desc = view.findViewById(R.id.tv_desc);// 给控件设置好数据iv_icon.setImageResource(mPlanets.get(position).image);tv_name.setText(mPlanets.get(position).name);tv_desc.setText(mPlanets.get(position).desc);return view;}}
public class BaseAdapterActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {private Spinner sp_base;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_base_adapter);sp_base = findViewById(R.id.sp_base);CustomBaseAdapter adapter = new CustomBaseAdapter(this, Planet.getPlanets());sp_base.setAdapter(adapter);sp_base.setSelection(0);sp_base.setOnItemSelectedListener(this);}@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position, long id) {ToastUtil.show(this, "选中了" + parent.getItemAtPosition(position));}@Overridepublic void onNothingSelected(AdapterView<?> parent) {}
}
当列表的Item从上方滚出屏幕视角之外:
复用convertView
public class CustomBaseAdapter extends BaseAdapter {private Context mContext;private List<Planet> mPlanets;public CustomBaseAdapter(Context context, List<Planet> planets) {mContext = context;mPlanets = planets;}@Overridepublic int getCount() {return mPlanets.size();}@Overridepublic Object getItem(int position) {return mPlanets.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder viewHolder;if(convertView == null){convertView= LayoutInflater.from(mContext).inflate(R.layout.item_list, null);viewHolder = new ViewHolder();viewHolder.iv_icon = convertView.findViewById(R.id.iv_icon);viewHolder.tv_name = convertView.findViewById(R.id.tv_name);viewHolder.tv_desc = convertView.findViewById(R.id.tv_desc);// 将视图持有者保存到转换视图中convertView.setTag(viewHolder);}else{viewHolder = (ViewHolder) convertView.getTag();}// 给控件设置好数据viewHolder.iv_icon.setImageResource(mPlanets.get(position).image);viewHolder.tv_name.setText(mPlanets.get(position).name);viewHolder.tv_desc.setText(mPlanets.get(position).desc);return convertView;}public final class ViewHolder{public ImageView iv_icon;public TextView tv_name;public TextView tv_desc;}}
2.列表视图ListView
ListView允许在页面上分行展示数据列表,例如新闻列表、商品列表等,方便用户浏览与操作。
<ListViewandroid:id="@+id/lv_planet"android:layout_width="match_parent"android:layout_height="wrap_content"android:divider="@null"android:dividerHeight="0dp"android:listSelector="@color/transparent"/>
public class ListViewActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, CompoundButton.OnCheckedChangeListener {private ListView lv_planet;private List<Planet> planetList;private CheckBox ck_divider;private CheckBox ck_selector;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_list_view);lv_planet = findViewById(R.id.lv_planet);ck_divider = findViewById(R.id.ck_divider);ck_selector = findViewById(R.id.ck_selector);ck_divider.setOnCheckedChangeListener(this);ck_selector.setOnCheckedChangeListener(this);planetList = Planet.getPlanets();CustomBaseAdapter adapter = new CustomBaseAdapter(this, planetList);lv_planet.setAdapter(adapter);lv_planet.setOnItemClickListener(this);}@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {ToastUtil.show(this, "点击了:" + planetList.get(position).name);}@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {switch (buttonView.getId()){case R.id.ck_divider:if(ck_divider.isChecked()){// 从资源文件获取图形对象Drawable drawable = getResources().getDrawable(R.color.black,getTheme());lv_planet.setDivider(drawable);lv_planet.setDividerHeight(Utils.dip2px(this,1));}else{// 隐藏分割线lv_planet.setDivider(null);lv_planet.setDividerHeight(0);}break;case R.id.ck_selector:// 显示按压背景if (ck_selector.isChecked()){lv_planet.setSelector(R.drawable.list_selector);}else{Drawable drawable = getResources().getDrawable(R.color.transparent, getTheme());lv_planet.setSelector(drawable);}break;}}
}
ListView会出现条目事件冲突,比如每个条目具有点击事件,每个条目中的按钮同样具有点击事件,那么这样我们点击条目是不会出现任何响应。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="match_parent"android:layout_height="wrap_content"android:descendantFocusability="blocksDescendants"><!-- blocksDescendants 可阻止下级控件获取焦点,避免阻塞列表视图的点击事件--><ImageViewandroid:id="@+id/iv_icon"android:layout_width="0dp"android:layout_weight="1"android:layout_height="80dp"android:scaleType="fitCenter" /><LinearLayoutandroid:layout_width="0dp"android:layout_weight="3"android:layout_height="match_parent"android:orientation="vertical"android:layout_marginLeft="5dp"><TextViewandroid:id="@+id/tv_name"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:gravity="start|center"android:textColor="@color/black"android:textSize="20sp"/><TextViewandroid:id="@+id/tv_desc"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="2"android:gravity="start|center"android:textColor="@color/black"android:layout_marginTop="5dp"android:textSize="13sp"/></LinearLayout><Buttonandroid:id="@+id/btn_oper"android:layout_width="wrap_content"android:layout_height="match_parent"android:text="点我"android:gravity="center"android:layout_marginLeft="5dp"android:layout_marginRight="5dp"/>
</LinearLayout>
3.网格视图GridView
网格视图用于分行分列显示表格信息。
XML中的属性 | GridView类的设置方法 | 说明 |
---|---|---|
horizontalSpacing | setHorizontalSpacing | 指定网格项在水平方向的间距 |
verticalSpacing | setVerticalSpacing | 指定网格项在垂直方向的间距 |
numColumns | setNumColumns | 指定列的数目 |
stretchMode | setStretchMode | 指定剩余控件的拉伸模式 |
columnWidth | setColumnWidth | 指定每列的宽度 |
XML中的拉伸模式 | GridView类的拉伸模式 | 说明 |
---|---|---|
none | NO_STRETCH | 不拉伸 |
columnWidth | STRETCH_COLUMN_WIDTH | 若有剩余空间,则拉伸列宽挤掉空隙 |
spacingWidth | STRETCH_SPACING | 若有剩余空间,则列宽不变,把空间分配到每列间的空隙 |
spacingWidthUniform | STRETCH_SPACING_UNIFORM | 若有剩余空间,则列宽不变,把空间分配到每列左右的空隙 |
4.翻页视图ViewPager
ViewPager翻页时图允许页面在水平方向左右滑动。
public class ViewPagerActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {private ViewPager vp_content;private List<GoodsInfo> goodsInfoList;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_view_pager);vp_content = findViewById(R.id.vp_content);goodsInfoList = GoodsInfo.getDefaultList();ImagePagerAdapter adapter = new ImagePagerAdapter(this, goodsInfoList);vp_content.setAdapter(adapter);vp_content.addOnPageChangeListener(this);}/*** 当页面正在滑动时调用,参数包括当前项位置、偏移量及偏移像素值。* position:当前页面,及你点击滑动的页面。* positionOffset:当前页面偏移的百分比,百分比范围:0~1。* positionOffsetPixels:当前页面偏移的像素位置。*/@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}/*** 当新的页面被选中时调用,参数为新选中页面的位置。*/@Overridepublic void onPageSelected(int position) {ToastUtil.show(this, "当前页面位置:" + position);}/*** 页面滚动状态改变时调用,参数表示新的状态。* state:0表示当前页面被完全显示出来;1表示正在滑动,2表示滑动结束,但是没有被完全显示出来。*/@Overridepublic void onPageScrollStateChanged(int state) {}
}
public class ImagePagerAdapter extends PagerAdapter {private Context mContext;private List<GoodsInfo> mList;private List<ImageView> mViewList = new ArrayList<>();public ImagePagerAdapter(Context mContext, List<GoodsInfo> mList) {this.mContext = mContext;this.mList = mList;// 每个商品分配一个专用的图像视图this.mViewList = mList.stream().map(item -> {ImageView imageView = new ImageView(mContext);imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));imageView.setImageResource(item.pic);return imageView;}).collect(Collectors.toList());}@Overridepublic int getCount() {return mViewList.size();}@Overridepublic boolean isViewFromObject(@NonNull View view, @NonNull Object object) {return view == object;}// 实例化到指定位置的页面,并将其添加到容器中@NonNull@Overridepublic Object instantiateItem(@NonNull ViewGroup container, int position) {// 添加一个view到container中,而后返回一个跟这个view可以关联起来的对象ImageView item = mViewList.get(position);container.addView(item);return item;}// 从容器中销毁指定位置的页面@Overridepublic void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {container.removeView(mViewList.get(position));}
}
5.翻页标签栏pagerTabStrip
public class PagerTabActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {private List<GoodsInfo> mGoodsInfoList;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_pager_tab);initPagerStrip();initViewPager();}// 初始化翻页视图private void initViewPager() {ViewPager vp_content = findViewById(R.id.vp_content);mGoodsInfoList = GoodsInfo.getDefaultList();vp_content.setAdapter(new ImagePagerAdapter(this, mGoodsInfoList));vp_content.addOnPageChangeListener(this);vp_content.setCurrentItem(3);}// 初始化翻页标签栏private void initPagerStrip() {PagerTabStrip pts_tab = findViewById(R.id.pts_tab);// 设置标签栏文本大小pts_tab.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);pts_tab.setTextColor(Color.BLACK);}@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}@Overridepublic void onPageSelected(int position) {ToastUtil.show(this,"您翻到的手机品牌是" + mGoodsInfoList.get(position).name );}@Overridepublic void onPageScrollStateChanged(int state) {}
}
public class ImagePagerAdapter extends PagerAdapter {private Context mContext;private List<GoodsInfo> mList;private List<ImageView> mViewList = new ArrayList<>();public ImagePagerAdapter(Context mContext, List<GoodsInfo> mList) {this.mContext = mContext;this.mList = mList;// 每个商品分配一个专用的图像视图this.mViewList = mList.stream().map(item -> {ImageView imageView = new ImageView(mContext);imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));imageView.setImageResource(item.pic);return imageView;}).collect(Collectors.toList());}@Overridepublic int getCount() {return mViewList.size();}@Overridepublic boolean isViewFromObject(@NonNull View view, @NonNull Object object) {return view == object;}// 实例化到指定位置的页面,并将其添加到容器中@NonNull@Overridepublic Object instantiateItem(@NonNull ViewGroup container, int position) {// 添加一个view到container中,而后返回一个跟这个view可以关联起来的对象ImageView item = mViewList.get(position);container.addView(item);return item;}// 从容器中销毁指定位置的页面@Overridepublic void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {container.removeView(mViewList.get(position));}@Nullable@Overridepublic CharSequence getPageTitle(int position) {return mList.get(position).name;}
}
<?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:tools="http://schemas.android.com/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".PagerTabActivity"><androidx.viewpager.widget.ViewPagerandroid:id="@+id/vp_content"android:layout_marginTop="50dp"android:layout_width="match_parent"android:layout_height="400dp"><androidx.viewpager.widget.PagerTabStripandroid:id="@+id/pts_tab"android:layout_width="wrap_content"android:layout_height="wrap_content"/></androidx.viewpager.widget.ViewPager></LinearLayout>
6.ViewPager实现引导页
当用户安装一个新的应用时,首次启动大多出现欢迎页面,这个引导页要往右翻翻好几页,才会进入应用主页,这种启动引导页就是通过翻页视图实现的。
public class LaunchSimpleAdapter extends PagerAdapter {private List<View> mViewList = new ArrayList<>();/*** 构造函数,用于初始化适配器并填充页面数据。** @param context 上下文对象* @param imageArray 图片资源数组*/public LaunchSimpleAdapter(Context context, int[] imageArray) {for (int i = 0; i < imageArray.length; i++) {// 从布局文件中加载页面视图View view = LayoutInflater.from(context).inflate(R.layout.item_launch, null);// 获取 ImageView 并设置图片资源ImageView iv_launch = view.findViewById(R.id.iv_launch);iv_launch.setImageResource(imageArray[i]);// 获取 RadioGroupRadioGroup rg_indicate = view.findViewById(R.id.rg_indicate);// 获取 ButtonButton btn_start = view.findViewById(R.id.btn_start);// 为每个页面添加一组 RadioButtonfor (int j = 0; j < imageArray.length; j++) {RadioButton radioButton = new RadioButton(context);radioButton.setLayoutParams(new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));radioButton.setPadding(10, 10, 10, 10);rg_indicate.addView(radioButton);}// 设置当前页面对应的 RadioButton 为选中状态((RadioButton) rg_indicate.getChildAt(i)).setChecked(true);// 如果是最后一个页面,则显示按钮并设置点击事件if (i == imageArray.length - 1) {btn_start.setVisibility(View.VISIBLE);btn_start.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {ToastUtil.show(context, "点击了开始体验");}});} else {// 如果不是最后一个页面,则隐藏按钮btn_start.setVisibility(View.GONE);}// 将整个页面视图添加到 mViewList 中mViewList.add(view);}}@Overridepublic int getCount() {// 返回页面数量return mViewList.size();}@Overridepublic boolean isViewFromObject(@NonNull View view, @NonNull Object object) {// 判断给定的视图是否来自指定的对象return view == object;}@NonNull@Overridepublic Object instantiateItem(@NonNull ViewGroup container, int position) {// 创建并返回指定位置的页面视图View view = mViewList.get(position);container.addView(view);return view;}@Overridepublic void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {// 移除指定位置的页面视图container.removeView(mViewList.get(position));}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="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"><ImageViewandroid:id="@+id/iv_launch"android:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="fitXY"/><RadioGroupandroid:id="@+id/rg_indicate"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_centerHorizontal="true"android:paddingBottom="20dp"android:orientation="horizontal"/><Buttonandroid:id="@+id/btn_start"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:text="立即开始美好生活"android:textColor="@color/black"android:textSize="22sp"android:visibility="gone"/></RelativeLayout>
7.碎片Fragment
传统的Activity并不能很好的处理大屏问题,所以急需一个碎片化的东西能够划区域展示内容,且有自己的独立可操作空间,所以就出现了Fragment。
静态注册在布局文件中直接指定Fragment,而动态注册直到代码中才动态添加Fragment。
1.Fragment静态注册
public class FragmentStaticActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_fragment_static);}
}
public class StaticFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_static, container, false);}
}
<?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:tools="http://schemas.android.com/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".FragmentStaticActivity"><fragmentandroid:id="@+id/fragment_static"android:name="com.zzzjian.demo6.fragment.StaticFragment"android:layout_width="match_parent"android:layout_height="60dp"/><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="每个页面具体的内容"android:textColor="@color/black"android:gravity="center"android:textSize="17sp"/></LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"android:orientation="horizontal"android:background="#bbffbb"tools:context=".fragment.StaticFragment"><TextViewandroid:id="@+id/tv_adv"android:layout_width="0dp"android:layout_weight="1"android:layout_height="match_parent"android:text="广告图片"android:textColor="@color/black"android:gravity="center"android:textSize="17sp"/><ImageViewandroid:id="@+id/iv_adv"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="4"android:src="@drawable/ikun"android:scaleType="fitCenter"/></LinearLayout>
2.Fragment生命周期
public class StaticFragment extends Fragment {private static final String TAG = "StaticFragment";@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_static, container, false);}@Overridepublic void onAttach(@NonNull Context context) {super.onAttach(context);Log.d(TAG, "onAttach ");}@Overridepublic void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);Log.d(TAG, "onCreate ");}@Overridepublic void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {super.onViewCreated(view, savedInstanceState);Log.d(TAG, "onViewCreated ");}@Overridepublic void onStart() {super.onStart();Log.d(TAG, "onStart ");}@Overridepublic void onResume() {super.onResume();Log.d(TAG, "onResume ");}@Overridepublic void onActivityCreated(@Nullable Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);Log.d(TAG, "onActivityCreated ");}@Overridepublic void onPause() {super.onPause();Log.d(TAG, "onPause ");}@Overridepublic void onStop() {super.onStop();Log.d(TAG, "onStop ");}@Overridepublic void onDestroyView() {super.onDestroyView();Log.d(TAG, "onDestroyView ");}@Overridepublic void onDestroy() {super.onDestroy();Log.d(TAG, "onDestroy ");}@Overridepublic void onDetach() {super.onDetach();Log.d(TAG, "onDetach ");}
}
3.Fragment动态注册
ublic class FragmentDynamicActivity extends AppCompatActivity {private ViewPager vp_content;private PagerTabStrip pts_tab;private List<GoodsInfo> mGoodsList;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_fragment_dynamic);initPagerStrip();initViewPager();}private void initViewPager() {vp_content = findViewById(R.id.vp_content);mGoodsList = GoodsInfo.getDefaultList();MobilePagerAdapter adapter = new MobilePagerAdapter(getSupportFragmentManager(), mGoodsList);vp_content.setAdapter(adapter);vp_content.setCurrentItem(0);}private void initPagerStrip() {pts_tab = findViewById(R.id.pts_tab);pts_tab.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);pts_tab.setTextColor(Color.BLACK);}
}
public class DynamicFragment extends Fragment {public static DynamicFragment newInstance(int position,int image_id,String desc) {DynamicFragment fragment = new DynamicFragment();// 把参数打包传入fragment中Bundle args = new Bundle();args.putInt("position",position);args.putInt("image_id", image_id);args.putString("desc", desc);fragment.setArguments(args);return fragment;}/*** 创建碎片视图*/@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment_dynamic, container, false);ImageView iv_pic = (ImageView) view.findViewById(R.id.iv_pic);TextView tv_desc = (TextView) view.findViewById(R.id.tv_desc);if(getArguments() != null){iv_pic.setImageResource(getArguments().getInt("image_id"));tv_desc.setText(getArguments().getString("desc"));}return view;}
}
public class MobilePagerAdapter extends FragmentPagerAdapter {private List<GoodsInfo> mGoodsList;public MobilePagerAdapter(@NonNull FragmentManager fm, List<GoodsInfo> goodsInfoList) {super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);this.mGoodsList = goodsInfoList;}@NonNull@Overridepublic Fragment getItem(int position) {GoodsInfo info = mGoodsList.get(position);return DynamicFragment.newInstance(position, info.pic ,info.description);}@Overridepublic int getCount() {return mGoodsList.size();}@Nullable@Overridepublic CharSequence getPageTitle(int position) {return mGoodsList.get(position).name;}
}