欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android自定义控件之创建可复用的组合控件

程序员文章站 2024-02-26 21:14:40
前面已学习了一种自定义控件的实现,是andriod 自定义控件之音频条,还没学习的同学可以学习下,学习了的同学也要去温习下,一定要自己完全的掌握了,再继续学习,贪多嚼不烂可...

前面已学习了一种自定义控件的实现,是andriod 自定义控件之音频条,还没学习的同学可以学习下,学习了的同学也要去温习下,一定要自己完全的掌握了,再继续学习,贪多嚼不烂可不是好的学习方法,我们争取学习了一种技术就会一种技术,而且不光看了就算了,最好的方法就是看完我自己再练习下,再扩展下,在原来的基础上在添加一些东西,比如,增加一些功能实现等等。

今天我们打算学习下另外一种自定义控件,就是创建可重复使用的组合控件,那么问题来了:

什么是可重复使用?
就是在应用中,可以在多个地方共同使用一套代码。这样不仅能减少我们的工作量,而且还能保持应用风格的一致,这种应用最多最直接的体现就是统一风格样式的标题栏。

那什么又是组合控件呢?
组合控件,顾名思义就是多个控件组合在一起,相互协作共同完成某些特定的功能。

下面我们就针对app应用中风格统一的标题栏来开始我们的学习。

首先,既然是一组组合的控件,那就必须有一个可以来包含这些控件的容器,我们所接触的可以存放控件的容器很多,比如linearlayout、relativelayout等等多种layout,今天我们就选择relativelayout来做我们的容器。和以前一样,我们先定义一个compositeviews类来继承relativelayout类,并重写它的构造方法,代码如下:

public class compositeviews extends relativelayout{

 public compositeviews(context context) {
  this(context,null);
 }
 public compositeviews(context context, attributeset attrs) {
  this(context, attrs,0);
 }
 public compositeviews(context context, attributeset attrs, int defstyleattr) {
  super(context, attrs, defstyleattr);
 }
 }

接下来,我们再定义三个textview控件,分别是mlefetext,mrighttext,texttitle用来显示“返回”,“搜索”以及“标题”并且使用layoutparams规定它们在容器里面的对齐方式。请看代码:

public class compositeviews extends relativelayout{
 private textview mlefetext;
 private textview mrighttext;
 private textview texttitle;
 private layoutparams leftlayoutparams;
 private layoutparams ridhtlayoutparams;
 private layoutparams titlelayoutparams;

 public compositeviews(context context) {
  this(context,null);
 }
 public compositeviews(context context, attributeset attrs) {
  this(context, attrs,0);
 }
 public compositeviews(context context, attributeset attrs, int defstyleattr) {
  super(context, attrs, defstyleattr);
  initview(context);
 }

initview(context)方法中是用来初始化三个组合控件的,请看:

 private void initview(context context) {
  mlefetext = new textview(context);
  mrighttext = new textview(context);
  texttitle = new textview(context);
  /*
   * 左按钮位置
   */
  leftlayoutparams = new layoutparams(layoutparams.wrap_content, layoutparams.wrap_content);
  leftlayoutparams.addrule(relativelayout.align_parent_left,true);
  mlefetext.settext("返回");
  mlefetext.settextsize(22);
  /*
   * 右按钮位置
   */
  ridhtlayoutparams = new layoutparams(layoutparams.wrap_content, layoutparams.wrap_content);
  ridhtlayoutparams.addrule(relativelayout.align_parent_right,true);
  mrighttext.settext("搜索");
  mrighttext.settextsize(22);
  /*
   * 中间标题位置
   */
  titlelayoutparams = new layoutparams(layoutparams.wrap_content, layoutparams.wrap_content);
  titlelayoutparams.addrule(relativelayout.center_in_parent,true);
  texttitle.settext("这是一个标题");
  texttitle.settextsize(22);
 }

ok,以上的代码已经实现了组合控件的显示和对齐方式,我们把定义的view添加到布局文件中并在activity加载吧

activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:custom="http://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:background="#999999"
 android:layout_height="wrap_content"
 android:orientation="vertical">

 <com.sanhuimusic.mycustomview.view.compositeviews
  android:id="@+id/topbar"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  />
</linearlayout>

mainactivity:

public class mainactivity extends appcompatactivity{
 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
 }
}

我们先来运行看下结果

Android自定义控件之创建可复用的组合控件

ok,已显示出来了,但是相信大家也看出来了,这上面的代码中,各个控件中的属性是都是我们固定写死的,既然我们是创建可服用的控件,固定写死的东西肯定是不可取的,那么我们怎么可以灵活地获取控件的属性,以至于能达到复用呢?

这就必须要接触另外一种技术了,就是自定义属性。用我们自定义的属于可以在每次使用我们定义的控件时为其分配属性即可。下面我们来学习下自定义属性。

自定义属性其实也是相当的简单,首先,我们现在资源文件res下values目录下新建一个attrs.xml文件(eclipse自带,as自建),新建的attrs.xml是一个包含如下代码的文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>

</resources>

在resources中有各种属性供我们使用,同学们可以自己看下。根据我们现在的需求,我们选择使用declare-styleable来声明我们的属性集,然后为其定义特有的name属性,这个name是供我们在使用自定义属性时,通过它可以查找到里面的所有属性。请看如下代码:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <declare-styleable name="compositeviews">
  <attr name="titletext" format="string"/>
  <attr name="titletextsize" format="dimension"/>
  <attr name="titlecolor" format="color"/>
  <attr name="titlebackground" format="color|reference"/>

  <attr name="lefttextcolor" format="color"/>
  <attr name="leftbackground" format="color|reference"/>
  <attr name="lefttext" format="string"/>
  <attr name="lefttextsize" format="dimension"/>

  <attr name="righttextcolor" format="color"/>
  <attr name="rightbackground" format="color|reference"/>
  <attr name="righttext" format="string"/>
  <attr name="righttextsize" format="dimension"/>
 </declare-styleable>

</resources>

单独拿一行属性来解析下它所代表的含义:如

好了,自定义属性我们已学习完毕,那么该怎么使用我们自己定义的属性呢?其实也很简单,在我们的activity_main.xml文件中直接使用我们定义的属性就可以了,但是在使用是之前必须在指定引用第三方控件的命名空间,在跟布局文件中添加如下一行代码:

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

custom是我们第三方命名空间的名字,可以任意命名,我们在使用自定义属性时必须以它开头。请看代码:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:custom="http://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:background="#999999"
 android:layout_height="wrap_content"
 android:orientation="vertical">

 <com.sanhuimusic.mycustomview.view.compositeviews
  android:id="@+id/topbar"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"

  custom:titletext="@string/titletext"
  custom:titlecolor="#000000"
  custom:titletextsize="@dimen/titletextsize"
  custom:titlebackground="#999999"
  custom:lefttext="@string/lefttext"
  custom:lefttextcolor="#ffffff"
  custom:leftbackground="#666666"
  custom:lefttextsize="@dimen/lefttextsize"
  custom:righttext="@string/righttext"
  custom:righttextcolor="#ffffff"
  custom:rightbackground="#666666"
  custom:righttextsize="@dimen/righttextsize"
  />
 
</linearlayout>

我们是使用custom加上我们自定义属性里面< attr name="titletext" format="string"/>里的name值来动态设置属性值的,如:custom:titletext="@string/titletext"。

ok,在我们xml文件中已设定好属性值,那么该怎么显示出来呢?这个是需要通过一个类型组typedarray来获取的,它里面包含各种从attributeset属性集中获取属性的方法,所以我们修改上面的构造方法和initview(context)方法,如下所示:

 private void initview(context context, attributeset attrs) {
  mlefetext = new textview(context);
  mrighttext = new textview(context);
  texttitle = new textview(context);

  /**
   * 获取自定义属性
   */
  typedarray typedarray = context.obtainstyledattributes(attrs, r.styleable.compositeviews);
  string titletext = typedarray.getstring(r.styleable.compositeviews_titletext);
  float titletextsize = typedarray.getdimension(r.styleable.compositeviews_titletextsize, 16);
  int titlecolor = typedarray.getcolor(r.styleable.compositeviews_titlecolor,0);
  drawable titlebackground = typedarray.getdrawable(r.styleable.compositeviews_titlebackground);

  string lefttext = typedarray.getstring(r.styleable.compositeviews_lefttext);
  int lefttextcolor = typedarray.getcolor(r.styleable.compositeviews_lefttextcolor, 0);
  float lefttextsize = typedarray.getdimension(r.styleable.compositeviews_lefttextsize, 16);
  drawable leftbackground = typedarray.getdrawable(r.styleable.compositeviews_leftbackground);

  string righttext = typedarray.getstring(r.styleable.compositeviews_righttext);
  int righttextcolor = typedarray.getcolor(r.styleable.compositeviews_righttextcolor, 0);
  float righttextsize = typedarray.getdimension(r.styleable.compositeviews_righttextsize, 16);
  drawable rightbackground = typedarray.getdrawable(r.styleable.compositeviews_rightbackground);
  typedarray.recycle();
  /*
   * 左按钮位置
   */
  leftlayoutparams = new layoutparams(layoutparams.wrap_content, layoutparams.wrap_content);
  leftlayoutparams.addrule(relativelayout.align_parent_left,true);
  mlefetext.settext(lefttext);
  mlefetext.settextcolor(lefttextcolor);
  mlefetext.settextsize(lefttextsize);
  mlefetext.setbackground(leftbackground);
  addview(this.mlefetext,leftlayoutparams);
   /*
   * 右按钮位置
   */
  ridhtlayoutparams = new layoutparams(layoutparams.wrap_content, layoutparams.wrap_content);
  ridhtlayoutparams.addrule(relativelayout.align_parent_right,true);
  mrighttext.settext(righttext);
  mrighttext.settextcolor(righttextcolor);
  mrighttext.settextsize(righttextsize);
  mrighttext.setbackground(rightbackground);
  addview(mrighttext,ridhtlayoutparams);
  /*
   * 中间标题位置
   */
  titlelayoutparams = new layoutparams(layoutparams.wrap_content, layoutparams.wrap_content);
  titlelayoutparams.addrule(relativelayout.center_in_parent,true);
  texttitle.settext(titletext);
  texttitle.settextsize(titletextsize);
  texttitle.settextcolor(titlecolor);
  texttitle.setbackground(titlebackground);
  addview(texttitle,titlelayoutparams);
 }

代码解释:首先通过上下文context获取到属性存放到typedarray 中,然后通过typedarray 里封装好的各种方法获取对应的属性值,然后再分别为我们的控件设置属性。这样就完成了,自定义属性的使用,并且复用度高,每当需要使用标题栏是都只需要在xml中添加我们定义的view控件,为其配置属性即可使用,节约了开发时间,提高了效率,并且还保持的app风格的一致。

好,到这里感觉已经讲完了整个过程吧,其实还有一个重要的实现还没有讲。我们的控件已经可以呈现出来了,但是怎么完成里面控件的作用呢?

这里比较常见的做法是利用回调机制来实现功能的开发,首先我们先定义一个接口,创建两个方法,用于左右控件的点击事件。

 public interface topbarclicklistener{
   void leftclicklistener();
   void rightclicklistener();
 }

然后在构造方法中为左右控件添加点击事件,但不实现功能,等待调用者自己实现:

private void setlistener() {
  mlefetext.setonclicklistener(new onclicklistener() {
   @override
   public void onclick(view v) {
    mtopbarclicklistener.leftclicklistener();
   }
  });
  mrighttext.setonclicklistener(new onclicklistener() {
   @override
   public void onclick(view v) {
    mtopbarclicklistener.rightclicklistener();
   }
  });
 }

再者,把定义好的接口暴露给调用者:

 public void setontopbarclicklistener(topbarclicklistener topbarclicklistener){
  mtopbarclicklistener = topbarclicklistener;
 }

最后,谁调用,谁实现。这就完成了不同界面复用控件实现不同的功能的便利。在这里我们只在mainactivity中打印toast就可以了。

public class mainactivity extends appcompatactivity {
 private compositeviews topbar;
 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  topbar = (compositeviews) findviewbyid(r.id.topbar);
  topbar.setontopbarclicklistener(new compositeviews.topbarclicklistener(){
   @override
   public void leftclicklistener() {
    toastutil.maketext(mainactivity.this,"您点击了返回键",toast.length_short).show();
   }
   @override
   public void rightclicklistener() {
    toastutil.maketext(mainactivity.this,"您点击了搜索键",toast.length_short).show();
   }
  });
 }
}

ok,看看结果吧

Android自定义控件之创建可复用的组合控件

好,已经可以实现我们的需求了,是不是学会很多呢。

今天主要讲了android自定义view中另一种的实现,并且还学习了自定义属性,同学们下去好好消化下,并自己动手现实一两个例子吧,好了,今天就讲到这里,谢谢大家。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。