课工场 “微服私访”项目学习(五)

本文介绍了一个Android应用中的首页轮播图实现方式及个人中心界面自定义View的详细步骤。包括轮播图的布局文件设置、轮播图的动态加载与更新、自定义View的创建过程等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

课程地址

http://www.kgc.cn/android/28013.shtml

主要讲课内容,首页轮播和个人中心的自定义布局
效果图
这里写图片描述
这里写图片描述


课程源码

http://www.kgc.cn/bbs/post/154285.shtml

一。首页轮播的设置
二。自定义VIew实现个人中心,其实个人中心实现的方法很多的,这样实现也不知道是不是最好的,但是也是学习下


一。首页轮播

布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/white"
                android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/home_fragment_viewpager_h">

        <android.support.v4.view.ViewPager
            android:id="@+id/fragment_img_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/color_bottom_layout_bg"
            />

        <LinearLayout
            android:id="@+id/fragment_point_subscript"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="@dimen/home_fragment_point_bottom"
            android:orientation="horizontal"/>
    </RelativeLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="首页界面"
        android:textColor="@color/colorPrimary"
        android:textSize="22sp"/>
</RelativeLayout>
<LinearLayout
            android:id="@+id/fragment_point_subscript"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="@dimen/home_fragment_point_bottom"
            android:orientation="horizontal"/>

代表加载的轮播点

public class HomeFragment extends BaseFragment {

    private View view;//根布局
    private ViewPager vp;
    private List<View> views;//轮播图展示图片view
    private MViewpager vp_adapter;//viewpager适配器
    private Timer timer;//计时器
    private LinearLayout layout;//轮播图下标集合
    private int count = 0;//轮播图当前下标
    public final int GetImags = 1014;//获取广告图返回码
    private final int AnnFaild = 1011;//获取广告图失败返回码

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        LogUtils.i(TAG, "首页界面加载..........");
        initView();//初始化UI组件
        initdata();//初始化数据
        return view;
    }

    /**
     * 初始化控件加载
     */
    private void initView() {
        vp = (ViewPager) view.findViewById(R.id.fragment_img_viewpager);
        layout = (LinearLayout) view.findViewById(R.id.fragment_point_subscript);
    }

    /**
     * 初始化数据展示
     */
    private void initdata() {
        if (views == null) {
            views = new ArrayList<View>();
        }
        vp_adapter = new MViewpager();
        vp.setAdapter(vp_adapter);
        //添加界面滚动监听
        vp.addOnPageChangeListener(vp_adapter);
        //首页轮播图获取
        OkHttpManager.getInstance().getNet(Constant.Announcement, new OkHttpManager.ResultCallback() {
            @Override
            public void onFailed(Request request, IOException e) {
                getAnnFailure();
            }

            @Override
            public void onSuccess(String response) {
                getAnnSuccess(response);
            }
        });
    }

    /**
     * 从服务端获取公告信息失败
     * 此时展示数据库缓存数据
     */
    private void getAnnFailure() {
        //从数据库中获取数据
        List<AnnImgs> imgs_dblist = DataSupport.findAll(AnnImgs.class);
        if (imgs_dblist != null) {
            updateAnnShow(imgs_dblist);
        }
    }


    /**
     * 从服务端获取公告信息成功
     */
    private void getAnnSuccess(String resultImgs) {
        //服务端返回有效数据则展示,没有不做处理
        if (resultImgs != null && !"".equals(resultImgs)) {
            Gson gson = new Gson();
            AnnImageResult air = gson.fromJson(resultImgs, AnnImageResult.class);
            List<AnnImgs> imgs_list = air.getBody();
            if (imgs_list == null) {
                imgs_list = new ArrayList<AnnImgs>();
            }
            updateAnnShow(imgs_list);
            //更新缓存
            if (imgs_list.size() > 0) {
                //从数据库清除数据保存
                DataSupport.deleteAll(AnnImgs.class);
                //添加新数据到数据库
                DataSupport.saveAll(imgs_list);
            }
        }
    }

    /**
     * 根据公告图片地址动态更新界面
     *
     * @param imgs_dblist
     */
    private void updateAnnShow(List<AnnImgs> imgs_dblist) {
        views.clear();
        //动态创建轮播展示view
        for (int i = 0; i < imgs_dblist.size(); i++) {
            ImageView img = new ImageView(mActivity);
            img.setScaleType(ImageView.ScaleType.CENTER_CROP);
            //通过网络地址显示图片
            Picasso.with(mActivity)
                    .load(Constant.BaseUrl + imgs_dblist.get(i).getImgUrl())
                    .into(img);
            views.add(img);
        }
        //更新界面显示
        vp_adapter.notifyDataSetChanged();
        //添加指示器下标点
        initPoint();
        //开启任务计时器
        if (timer == null) {
            timer = new Timer();
            timer.schedule(task, 0, 3000);
        }
    }

    //创建viewpager适配器
    class MViewpager extends PagerAdapter implements ViewPager.OnPageChangeListener {
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

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

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

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(views.get(position));
            return views.get(position);
        }

        /**
         * viewpager滑动监听,动态更改指示下标的选中状态
         * @param position
         */
        @Override
        public void onPageSelected(int position) {
            for (int i = 0; i < layout.getChildCount(); i++) {
                ImageView image = (ImageView) layout.getChildAt(i);
                if (i == position) {
                    image.setSelected(true);
                } else {
                    image.setSelected(false);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Constant.Scroll://接收滚动消息,并执行
                    vp.setCurrentItem(count);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 创建图片变化下标图标
     */
    public void initPoint() {
        //清除所有指示下标
        layout.removeAllViews();
        for (int i = 0; i < views.size(); i++) {
            ImageView img = new ImageView(mActivity);
            //添加下标圆点参数
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            params.leftMargin = 5;
            params.rightMargin = 5;
            img.setLayoutParams(params);
            img.setImageResource(R.drawable.sns_v2_page_point);
            if (i == 0) {
                img.setSelected(true);
            }
            layout.addView(img);
        }
    }

    // 创建记时器发送图片轮播消息
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if (count == views.size()) {
                count = 0;
            } else {
                count = count + 1;
            }
            mHandler.sendEmptyMessage(Constant.Scroll);
        }
    };
}

其实网上还有很多写轮播图的框架,感觉应该比自己写的坑少一点吧


二。自定义View
1.先创建一个androidlib
在values中创建attrs
创建自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SetItemView">
        <attr name="leftText" format="string"/>
        <attr name="leftIcon" format="integer"/>
        <attr name="rightIcon" format="integer"/>
        <attr name="textSize" format="float"/>
        <attr name="textColor" format="color"/>
        <attr name="isShowUnderLine" format="boolean"/>
    </declare-styleable>
</resources>
SetItemView
public class SetItemView extends RelativeLayout {

    //页面对象
    private View mView;
    //页面跟布局
    private RelativeLayout mRootLayout;
    //左侧文字
    private TextView mTvLeftText;
    //左侧图标
    private ImageView mIvLeftIcon;
    //右侧图标
    private ImageView mIvRightIcon;
    //下划线
    private View mUnderLine;
    //显示文字
    private String mText;
    //文字颜色
    private int mTextColor;
    //文字大小
    private int mTextSize;
    //左侧图标
    private Drawable mLeftIcon;
    // 右侧图标
    private Drawable mRightIcon;
    //左侧边距
    private int mMarginLeft;
    //右侧边距
    private int mMarginRight;
    //定义监听器
    private OnSetItemClick mOnSetItemClick;

    public SetItemView(Context context) {
        this(context, null);
    }

    public SetItemView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SetItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
        getCustomStyle(context, attrs);
        //设置点击监听事件
        mRootLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mOnSetItemClick) {
                    mOnSetItemClick.click();
                }
            }
        });
    }

    /**
     * 初始化控件自定义属性信息
     *
     * @param context
     * @param attrs
     */
    private void getCustomStyle(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SetItemView);
        int num = typedArray.getIndexCount();
        for (int i = 0; i < num; i++) {
            int arr = typedArray.getIndex(i);
            if (arr == R.styleable.SetItemView_leftText) {
                mText = typedArray.getString(arr);
                mTvLeftText.setText(mText);
            } else if (arr == R.styleable.SetItemView_leftIcon) {
                mLeftIcon = typedArray.getDrawable(arr);
                mIvLeftIcon.setImageDrawable(mLeftIcon);
            } else if (arr == R.styleable.SetItemView_rightIcon) {
                mRightIcon = typedArray.getDrawable(arr);
                mIvRightIcon.setImageDrawable(mRightIcon);
            } else if (arr == R.styleable.SetItemView_textSize) {
                // 默认设置为16sp
                float textSize = typedArray.getFloat(arr, 16);
                mTvLeftText.setTextSize(textSize);
            } else if (arr == R.styleable.SetItemView_textColor) {
                //文字默认灰色
                mTextColor = typedArray.getColor(arr, Color.GRAY);
                mTvLeftText.setTextColor(mTextColor);
            } else if (arr == R.styleable.SetItemView_isShowUnderLine) {
                boolean flag = typedArray.getBoolean(arr, true);
                if (!flag) {
                    mUnderLine.setVisibility(View.GONE);
                }
            }
        }
        typedArray.recycle();
    }

    /**
     * 初始化控件对象
     */
    private void initView(Context context) {
        mView = View.inflate(context, R.layout.settingitem, this);
        mRootLayout = (RelativeLayout) mView.findViewById(R.id.rootLayout);
        mTvLeftText = (TextView) mView.findViewById(R.id.tv_lefttext);
        mIvLeftIcon = (ImageView) mView.findViewById(R.id.iv_lefticon);
        mIvRightIcon = (ImageView) mView.findViewById(R.id.iv_righticon);
        mUnderLine = mView.findViewById(R.id.underline);
    }

    public void setmOnSetItemClick(OnSetItemClick mOnSetItemClick) {
        this.mOnSetItemClick = mOnSetItemClick;
    }

    public interface OnSetItemClick {
        void click();
    }
}
settingitem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/rootLayout"
                android:layout_width="match_parent"
                android:layout_height="56dp"
                android:background="@drawable/bg"
                android:clickable="true"
                android:gravity="center_vertical">

    <ImageView
        android:id="@+id/iv_lefticon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="23dp"
        android:src="@drawable/clearcache"/>

    <TextView
        android:id="@+id/tv_lefttext"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@id/iv_lefticon"
        android:gravity="center_vertical"
        android:textSize="16sp"/>

    <ImageView
        android:id="@+id/iv_righticon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:layout_marginRight="23dp"
        android:src="@drawable/task_arrow"/>

    <View
        android:id="@+id/underline"
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:background="#99999999"/>
</RelativeLayout>

MeFragment

public class MeFragment extends BaseFragment {
    private View mView;
    private SetItemView mMeItem;
    private SetItemView mAboutItem;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //加载布局
        mView = inflater.inflate(R.layout.fragment_me, container, false);
        initView();

        return mView;
    }

    /**
     * 初始化控件信息
     */
    private void initView() {
        mMeItem = (SetItemView) mView.findViewById(R.id.rl_me);
        mAboutItem = (SetItemView) mView.findViewById(R.id.rl_about);

        mMeItem.setmOnSetItemClick(new SetItemView.OnSetItemClick() {
            @Override
            public void click() {
                Toast.makeText(mActivity, "点击了个人资料", Toast.LENGTH_SHORT).show();
            }
        });
        mAboutItem.setmOnSetItemClick(new SetItemView.OnSetItemClick() {
            @Override
            public void click() {
                Toast.makeText(mActivity, "点击了关于", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
<?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"
                android:id="@+id/root_layout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/white"
                android:orientation="vertical">


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f2f2f2">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:orientation="vertical">

                <ImageView
                    android:id="@+id/iv_header"
                    android:layout_width="@dimen/width_120"
                    android:layout_height="@dimen/height_120"
                    android:layout_marginTop="@dimen/margin_10"
                    android:src="@drawable/defaulthead"/>

                <TextView
                    android:id="@+id/tv_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/margin_7"
                    android:gravity="center"
                    android:text=""
                    android:textColor="#110d0a"
                    android:textSize="@dimen/textsize_16"/>

                <TextView
                    android:id="@+id/tv_job"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:gravity="center"
                    android:padding="@dimen/margin_13"
                    android:text=""
                    android:textColor="@color/text_color_9"
                    android:textSize="@dimen/textsize_14"/>
            </LinearLayout>

            <com.feng.settingitemlibrary.SetItemView
                android:id="@+id/rl_me"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:isShowUnderLine="false"
                app:leftIcon="@drawable/medata"
                app:leftText="@string/fragment_me_tv_me"
                app:rightIcon="@drawable/task_arrow"
                app:textColor="@color/text_color_6"
                app:textSize="16"/>

            <com.feng.settingitemlibrary.SetItemView
                android:id="@+id/rl_clear"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="14dp"
                app:leftIcon="@drawable/clearcache"
                app:leftText="@string/fragment_me_tv_clear"
                app:rightIcon="@drawable/task_arrow"
                app:textColor="@color/text_color_6"
                app:textSize="16"/>

            <com.feng.settingitemlibrary.SetItemView
                android:id="@+id/rl_feedback"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:leftIcon="@drawable/appfeedback"
                app:leftText="@string/fragment_me_tv_feedback"
                app:rightIcon="@drawable/task_arrow"
                app:textColor="@color/text_color_6"
                app:textSize="16"/>

            <com.feng.settingitemlibrary.SetItemView
                android:id="@+id/rl_about"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:leftIcon="@drawable/about"
                app:leftText="@string/fragment_me_tv_about"
                app:rightIcon="@drawable/task_arrow"
                app:textColor="@color/text_color_6"
                app:textSize="16"/>

            <com.feng.settingitemlibrary.SetItemView
                android:id="@+id/rl_version"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:leftIcon="@drawable/newversion"
                app:leftText="@string/fragment_me_tv_version"
                app:rightIcon="@drawable/task_arrow"
                app:textColor="@color/text_color_6"
                app:textSize="16"/>

            <com.feng.settingitemlibrary.SetItemView
                android:id="@+id/rl_exit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="30dp"
                android:layout_marginTop="14dp"
                app:isShowUnderLine="false"
                app:leftIcon="@drawable/appexit"
                app:leftText="@string/fragment_me_tv_exit"
                app:rightIcon="@drawable/task_arrow"
                app:textColor="@color/text_color_6"
                app:textSize="16"/>
        </LinearLayout>
    </ScrollView>

</RelativeLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值