zoukankan      html  css  js  c++  java
  • 自定义视图(组合控件)

    前言


      Android自定义控件主要分为两种,一种是通过继承View来实现自定义控件,另一种是通过组合已有到控件来实现自定义控件,上篇文章自定义视图(继承View)我们介绍了下继承View到方式,这篇文章简单介绍下组合控件来实现自定义控件。

      有些情况我们需要通过组合已有到控件来实现特定功能到控件组建,比如一个应用到题头,大概样式如下
        

    Java代码


      通过组合控件来实现自定义控件到方式,是通过继承一个ViewGrou对象来实现,比如LinearLayout, FrameLayout, RelativeLayout,等等,简单实现如下所示

      

     1 public class CombinView extends RelativeLayout {
     2 
     3     public CombinView(Context context, AttributeSet attrs) {
     4         super(context, attrs);
     5         LayoutInflater inflater = (LayoutInflater)context.getSystemService    (Context.LAYOUT_INFLATER_SERVICE);
     6         RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.custom_view,this);
     7 
     8     }
     9 
    10 }

      其中需要注意到是RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.custom_view,this);方法,第二个参数this,用来表明inflate出来到layout添加到当前对象

    custom_view.xml

      下面一段代码就是自定义视图的布局文件内容,没有什么特别的,如下所示

      

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:layout_width="match_parent"
     4     android:layout_height="wrap_content" >
     5 
     6     <TextView
     7         android:id="@+id/tvShow"
     8         android:layout_width="wrap_content"
     9         android:layout_height="wrap_content"
    10         android:text="返回" />
    11 
    12     <TextView
    13         android:layout_width="wrap_content"
    14         android:layout_height="wrap_content"
    15         android:layout_alignParentRight="true"
    16         android:text="设置" />
    17 
    18     <RelativeLayout
    19         android:layout_width="match_parent"
    20         android:layout_height="wrap_content" >
    21 
    22         <TextView
    23             android:layout_width="match_parent"
    24             android:layout_height="wrap_content"
    25             android:gravity="center_horizontal"
    26             android:text="标题" />
    27     </RelativeLayout>
    28 
    29 </RelativeLayout>

    后记

      这样的话,一个简单的组合自定义视图就实现完成了,这篇和上篇文章介绍了自定义视图的一些东西,虽然我们实现了自定义控件,但是还有一点没有提到,就是如何给自己的控件定制自己的属性,有了自己的属性才算完整,在下篇会简单介绍下自定义属性的一些东西。

    原文地址:http://www.cnblogs.com/luoaz/p/3983674.html

  • 相关阅读:
    Java生成登录随机验证码
    Java调用百度API实现人脸识别
    阿里云CentOS开放端口
    Windows环境下利用nginx作为图片服务器
    SpringCloud使用Feign调用服务,@ModelAttribute无法传递实体类参数
    Solr7正确的调用SolrClient姿势
    LeetCode 235. Lowest Common Ancestor of a Binary Search Tree(BST求最近公共祖先)
    LeetCode 538. Convert BST to Greater Tree(把BST每个节点的值都加上比它大的节点的值)
    Trie树模板例题
    Google KickStart 2020 RoundA
  • 原文地址:https://www.cnblogs.com/luoaz/p/3983674.html
Copyright © 2011-2022 走看看