Android自定义View的用法总结

本文参考了:http://greenrobot.me/devpost/android-custom-layout/Android SDK中提供了很多UI组件,如RelativeLayout, LinearLayout等,使用自定义控件有两大优点:1、通过减少View的使用来增加UI的显示效率2、构建SDK中没有的控件原文总结了4种自定义View,分别是Compo
摘要由CSDN通过智能技术生成
本文参考了:http://greenrobot.me/devpost/android-custom-layout/

Android SDK中提供了很多UI组件,如RelativeLayout, LinearLayout等,使用自定义控件有两大优点:
1、通过减少View的使用来增加UI的显示效率
2、构建SDK中没有的控件

原文总结了4种自定义View,分别是Composite View, Custom Composite View, Flat Custom View和Async Custom Views。示例代码在https://github.com/lucasr/android-layout-samples,可以直接运行。该工程依赖两个工程: Picasso  和 Smoothie .Picasso

 Picasso是一个异步图片加载库,Smoothie提供了异步加载ListView和GridView数据项的接口,使列表数据的加载更加顺滑。

本文只介绍Composite Vew 和 Custom Composite View的方法,这两种方式足够我们使用了,剩余两种方法需要自定义一套控制视图的框架,维护代价高,建议只用在app的核心且稳定的UI中,感兴趣的读者可自行研究。


Composite View
此方法是将多个View结合成一个可重用View的最简单方法,过程如下:
1、自定义控件,继承相应的控件。
2、在构造函数中填充一个merge布局
3、初始化自定义控件中的内部View

4、提供刷新View的接口

下面介绍了一个用法,该View的布局如下图所示:


首先是定义一个类文件TweetCompositeView.java

public class TweetCompositeView extends RelativeLayout implements TweetPresenter {
    private final ImageView mProfileImage;
    private final TextView mAuthorText;
    private final TextView mMessageText;
    private final ImageView mPostImage;
    private final EnumMap<Action, ImageView> mActionIcons;


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


    public TweetCompositeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);


        LayoutInflater.from(context).inflate(R.layout.tweet_composite_view, this, true);
        //初始化内部成员变量
        mProfileImage = (ImageView) findViewById(R.id.profile_image);
        mAuthorText = (TextView) findViewById(R.id.author_text);
        mMessageText = (TextView) findViewById(R.id.message_text);
        mPostImage = (ImageView) findViewById(R.id.post_image);


        mActionIcons = new EnumMap(Action.class);
        for (Action action : Action.values()) {
            final ImageView icon;
            switch (action) {
                case REPLY:
                    icon = (ImageView) findViewById(R.id.reply_action);
                    break;


                case RETWEET:
                    icon = (ImageView) findViewById(R.id.retweet_action);
                    break;


                case FAVOURITE:
                    icon = (ImageView) findViewById(R.id.favourite_action);
                    break;


                default:
                    throw new IllegalArgumentException("Unrecognized tweet action");
            }


            mActionIcons.put(action, icon);
        }
    }


    @Override
    public boolean shouldDelayChildPres
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值