Android高级控件

文章目录

1.下拉列表Spinner

1.数组适配器ArrayAdapter

最简单的适配器,只展示一行文字。

  1. 编写列表项的XML文件,内部布局只有一个TextView标签。
  2. 调用ArrayAdapter的构造方法,填入待展现的字符串数组,以及列表项的XML文件。
  3. 调用下拉框控件的setAdapter方法,传入第二部得到的适配器实例。
java 复制代码
public class SpinnerDropdownActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private final static String[] startArray = {"水星","金星","地球","火星","木星"};


    private Spinner sp_dropdown;

    @Override
    protected 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);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        ToastUtil.show(this, "选中了:" + startArray[position]);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}

2.简单适配器SimpleAdapter

SimpleAdapter允许在列表项中同时展示文本和图片。

java 复制代码
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;

    @Override
    protected 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);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        ToastUtil.show(this,"选中了:" + iconTextArray[position]);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}

3.基本适配器BaseAdapter

BaseAdapter是一种适应性更强的基本适配器。

java 复制代码
public class CustomBaseAdapter extends BaseAdapter {

    private Context mContext;

    private List<Planet> mPlanets;

    public CustomBaseAdapter(Context context, List<Planet> planets) {
        mContext = context;
        mPlanets = planets;
    }

    @Override
    public int getCount() {
        return mPlanets.size();
    }

    @Override
    public Object getItem(int position) {
        return mPlanets.get(position);
    }

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

    @Override
    public 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;
    }


}
java 复制代码
public class BaseAdapterActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private Spinner sp_base;

    @Override
    protected 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);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        ToastUtil.show(this, "选中了" + parent.getItemAtPosition(position));
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}

当列表的Item从上方滚出屏幕视角之外:

复用convertView

java 复制代码
public class CustomBaseAdapter extends BaseAdapter {

    private Context mContext;

    private List<Planet> mPlanets;

    public CustomBaseAdapter(Context context, List<Planet> planets) {
        mContext = context;
        mPlanets = planets;
    }

    @Override
    public int getCount() {
        return mPlanets.size();
    }

    @Override
    public Object getItem(int position) {
        return mPlanets.get(position);
    }

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

    @Override
    public 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允许在页面上分行展示数据列表,例如新闻列表、商品列表等,方便用户浏览与操作。

xml 复制代码
    <ListView
        android:id="@+id/lv_planet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="@null"
        android:dividerHeight="0dp"
        android:listSelector="@color/transparent"/>
java 复制代码
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;


    @Override
    protected 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);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ToastUtil.show(this, "点击了:" + planetList.get(position).name);
    }

    @Override
    public 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 复制代码
<?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 可阻止下级控件获取焦点,避免阻塞列表视图的点击事件-->

    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="80dp"
        android:scaleType="fitCenter" />


    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_marginLeft="5dp">

        <TextView
            android: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"/>

        <TextView
            android: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>


    <Button
        android: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翻页时图允许页面在水平方向左右滑动。

java 复制代码
public class ViewPagerActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {

    private ViewPager vp_content;
    private List<GoodsInfo> goodsInfoList;

    @Override
    protected 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:当前页面偏移的像素位置。
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    /**
     * 当新的页面被选中时调用,参数为新选中页面的位置。
     */
    @Override
    public void onPageSelected(int position) {
        ToastUtil.show(this, "当前页面位置:" + position);
    }

    /**
     * 页面滚动状态改变时调用,参数表示新的状态。
     * state:0表示当前页面被完全显示出来;1表示正在滑动,2表示滑动结束,但是没有被完全显示出来。
     */
    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
java 复制代码
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());
    }

    @Override
    public int getCount() {
        return mViewList.size();
    }

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


    // 实例化到指定位置的页面,并将其添加到容器中
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        // 添加一个view到container中,而后返回一个跟这个view可以关联起来的对象
        ImageView item = mViewList.get(position);
        container.addView(item);
        return item;
    }


    // 从容器中销毁指定位置的页面
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(mViewList.get(position));
    }
}

5.翻页标签栏pagerTabStrip

java 复制代码
public class PagerTabActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {

    private List<GoodsInfo> mGoodsInfoList;
    @Override
    protected 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);
    }

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

    }

    @Override
    public void onPageSelected(int position) {
        ToastUtil.show(this,"您翻到的手机品牌是" + mGoodsInfoList.get(position).name );
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
java 复制代码
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());
    }

    @Override
    public int getCount() {
        return mViewList.size();
    }

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


    // 实例化到指定位置的页面,并将其添加到容器中
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        // 添加一个view到container中,而后返回一个跟这个view可以关联起来的对象
        ImageView item = mViewList.get(position);
        container.addView(item);
        return item;
    }


    // 从容器中销毁指定位置的页面
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(mViewList.get(position));
    }


    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mList.get(position).name;
    }
}
xml 复制代码
<?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.ViewPager
        android:id="@+id/vp_content"
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="400dp">

        <androidx.viewpager.widget.PagerTabStrip
            android:id="@+id/pts_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </androidx.viewpager.widget.ViewPager>


</LinearLayout>

6.ViewPager实现引导页

当用户安装一个新的应用时,首次启动大多出现欢迎页面,这个引导页要往右翻翻好几页,才会进入应用主页,这种启动引导页就是通过翻页视图实现的。

java 复制代码
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]);

            // 获取 RadioGroup
            RadioGroup rg_indicate = view.findViewById(R.id.rg_indicate);

            // 获取 Button
            Button btn_start = view.findViewById(R.id.btn_start);

            // 为每个页面添加一组 RadioButton
            for (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() {
                    @Override
                    public void onClick(View v) {
                        ToastUtil.show(context, "点击了开始体验");
                    }
                });
            } else {
                // 如果不是最后一个页面,则隐藏按钮
                btn_start.setVisibility(View.GONE);
            }

            // 将整个页面视图添加到 mViewList 中
            mViewList.add(view);
        }
    }

    @Override
    public int getCount() {
        // 返回页面数量
        return mViewList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        // 判断给定的视图是否来自指定的对象
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        // 创建并返回指定位置的页面视图
        View view = mViewList.get(position);
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        // 移除指定位置的页面视图
        container.removeView(mViewList.get(position));
    }
}
xml 复制代码
<?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">

    <ImageView
        android:id="@+id/iv_launch"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"/>

    <RadioGroup
        android: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"/>

    <Button
        android: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静态注册

java 复制代码
public class FragmentStaticActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_static);
    }
}
java 复制代码
public class StaticFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_static, container, false);
    }
}
xml 复制代码
<?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">

    <fragment
        android:id="@+id/fragment_static"
        android:name="com.zzzjian.demo6.fragment.StaticFragment"
        android:layout_width="match_parent"
        android:layout_height="60dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="每个页面具体的内容"
        android:textColor="@color/black"
        android:gravity="center"
        android:textSize="17sp"/>

</LinearLayout>
xml 复制代码
<?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">

    <TextView
        android: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"/>

    <ImageView
        android: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生命周期

java 复制代码
public class StaticFragment extends Fragment {


    private static final String TAG = "StaticFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_static, container, false);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "onAttach ");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate ");
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated ");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart ");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume ");
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "onActivityCreated ");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause ");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop ");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy ");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "onDetach ");
    }
}

3.Fragment动态注册

java 复制代码
ublic class FragmentDynamicActivity extends AppCompatActivity {

    private ViewPager vp_content;

    private PagerTabStrip pts_tab;

    private List<GoodsInfo> mGoodsList;


    @Override
    protected 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);
    }
}
java 复制代码
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;
    }


    /**
     * 创建碎片视图
     */
    @Override
    public 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;
    }
}
java 复制代码
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
    @Override
    public Fragment getItem(int position) {
        GoodsInfo info = mGoodsList.get(position);
        return DynamicFragment.newInstance(position, info.pic ,info.description);
    }

    @Override
    public int getCount() {
        return mGoodsList.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mGoodsList.get(position).name;
    }
}
相关推荐
TheITSea3 分钟前
云服务器宝塔安装静态网页 WordPress、VuePress流程记录
java·服务器·数据库
AuroraI'ncoding10 分钟前
SpringMVC接收请求参数
java
九圣残炎35 分钟前
【从零开始的LeetCode-算法】3354. 使数组元素等于零
java·算法·leetcode
Y多了个想法40 分钟前
RK3568 android11 适配敦泰触摸屏 FocalTech-ft5526
android·rk3568·触摸屏·tp·敦泰·focaltech·ft5526
天天扭码1 小时前
五天SpringCloud计划——DAY1之mybatis-plus的使用
java·spring cloud·mybatis
程序猿小柒1 小时前
leetcode hot100【LeetCode 4.寻找两个正序数组的中位数】java实现
java·算法·leetcode
NotesChapter2 小时前
Android吸顶效果,并有着ViewPager左右切换
android
不爱学习的YY酱2 小时前
【操作系统不挂科】<CPU调度(13)>选择题(带答案与解析)
java·linux·前端·算法·操作系统
丁总学Java2 小时前
Maven项目打包,com.sun.tools.javac.processing
java·maven
kikyo哎哟喂2 小时前
Java 代理模式详解
java·开发语言·代理模式