Android 自定义view

在需求文案中有时候需要显示如下信息
1.点击某行显示详情ui,如下图
2.填充某行左由两边title信息.
3.箭头的动画.
通过上面需求定义了一个custom UIView
Demo code github传送点:https://github.com/wongstar/android-PullView

如图一所需要实现的需求。


Android 自定义view_第1张图片
图一

下面简单的分析所需要的知识点:
1.在attrs.xml中定义view 的style中属性,这些属性可以自定义如下:


        
        
        
        
        
        
        
        
        
        
        
        
        
        
 

如上述代码定义了当前行的左边text,textsize,textcolor ,当前行的右边的text,textsize,textcolor,visible,定义了是否存在moreview参数
format对应的是name相关属性的类别,具体的format对应的类别列表如下:
https://developer.android.com/reference/android/R.attr.html

在xml中调用attr中自定义的属性

xmlns:pullup="http://schemas.android.com/apk/res-auto"

要让xml中pullup的属性能够找到,需要在xml中声明xmlns:pullup的命名空间,这样后面的xml就能找到对应的attr中自定义的pullup属性,这一部非常重要,否则不能编译成功。

那在UIView中如何调用获取到对应的属性呢?

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.pullup);
CharSequence leftText = a.getText(R.styleable.pullup_leftText);
通过调用TypedArray就能获取到对应的参数,比如上面的pullup_leftText.
TypedArray是android framework层通过解析xml获取到xml中属性值.通过context来获取到。具体可以参考LayoutInflater 源码

再分析下PullUpView的构造。
public class PullUpView extends LinearLayout implements View.OnClickListener

1.该view是继承LinearLayout,这样你的detailView就可以直接add进去
2.设置当前LinearLayout的Orientation是VERTICAL
3.该view的第一个view是LayoutInflater一个FrameLayout具体如下:


        
        
    

        
    
    

通过LayoutInflater 把framelayout xml inflater到该LinearLayout中
LayoutInflater inflater = LayoutInflater.from(context);
rlTop = (FrameLayout) inflater.inflate(R.layout.menu_item_top_view,
null);
addView(rlTop, 0);
setOrientation(VERTICAL);//

通过上述的方式,把framelayout add到LinearLayout中

最后就是show Detail view 和hideDetailView,注意点是:Child的index是从1开始计算:

private void showViews() {
    for (int i = 1; i < getChildCount(); i++) {
        getChildAt(i).setVisibility(View.VISIBLE);
        }
    }
private void hideViews() {
        for (int i = 1; i < getChildCount(); i++) {
        getChildAt(i).setVisibility(View.GONE);
    }
}

得出来的整体UI效果图如下(图二)所示:


Android 自定义view_第2张图片
图二
想随时了解我的动态,欢迎大家关注我的个人公众号蚁农之家
蚁农之家.jpg

你可能感兴趣的:(Android 自定义view)