Custom View (ii) (Android Heroes)

Source: Internet
Author: User
Tags getcolor

The content is Bo master according to the book knocked out, Bo main code word very hard, reproduced please indicate the source, after the subsequent content will code out.

The previous custom view (i) (Android) is about extending the existing controls , which introduces the second custom view method to Create a composite control .

To create a composite control

Creating a composite control is a good way to create a collection of controls with reusable functionality. In this way, it is often necessary to inherit a suitable viewgroup, and then add the controls that specify the functionality to the group, thus synthesizing the new composite control. By creating a control in this way, we typically assign it some configurable properties to make it more extensible. Here's an example of how to create a composite control with a topbar.
We know that for application-style unification, many applications have a common UI interface, such as the Topbar, shown in the title bar.




Typically, these interfaces are abstracted out to form a common UI component. All interfaces that need to add a title bar will reference such a topbar, rather than each interface writing such a topbar in the layout file. At the same time, the designer can add the interface to Topbar, so that the caller can control the Topbar more flexibly, which can not only improve the reuse rate of the interface, but also make quick changes when the UI needs to be modified, without having to modify the title bar of each page.
Let's take a look at how to create a UI template like this. First, the template should be versatile and customizable. That is, we need to give the caller a rich interface so that they can change the text, color, behavior and other information in the template, not all templates are the same, then lost the meaning of the template.

Defining properties

Providing a customizable property for a view is as simple as creating a Attrs.xml property definition file under the values directory of the RES resource directory and defining the appropriate properties in the file with the following code.

<?xml version="1.0"encoding="Utf-8"?> <resources> <declare-styleable name="Topbar"> <attr name="_title"format="string"/> <attr name="_titletextsize"format="Dimension"/> <attr name="_titletextcolor"format="Color"/> <attr name="Lefttextcolor"format="Color"/> <attr name="Leftbackground"format="Reference|color"/> <attr name="Lefttext"format="string"/> <attr name="Righttextcolor"format="Color"/> <attr name="Rightbackground"format="Reference|color"/> <attr name="Righttext"format="string"/> </declare-styleable></resources>

We declare using a custom property in our code through a tag and determine the name of the reference through the Name property. Finally, the specific custom attributes are declared by tags, such as the font, size, color of the caption text, the text color of the left button, the background, the font, the text color of the right button, the background, the font, and so on, and specify the type of the property through the Format property. It is important to note that some properties can be either a color attribute or a reference property. such as the background of the button, you can specify it as a specific color, you can also designate it as a picture, so use the "|" To separate the different attributes--"Reference|color".
After you have determined the properties, you can create a custom control--topbar and let it inherit from ViewGroup, combining some of the required controls. Here for the sake of simplicity, we inherit relativelayout. In the construction method, get the custom attributes in the XML layout file by using the code shown below, just as we used the system-provided properties.

TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);

The system provides a data structure such as Typedarray to get a custom set of properties, followed by a reference to the Styleable Topbar, which is the name we specify in the XML. Next, by Typedarray the object's GetString (), GetColor (), and so on, you can get the property values for these definitions, as shown in the code below.

//Use this method to store all the attribute values of the declare-styleable you have defined in Attrs.xml into TypedarrayTypedArray ta = context.obtainstyledattributes (attrs, R.styleable.topbar);//Remove the corresponding value from the Typedarray to assign a value to the property you want to setMlefttextcolor = Ta.getcolor (R.styleable.topbar_lefttextcolor,0); mleftbackground = Ta.getdrawable (r.styleable.topbar_leftbackground); mlefttext = Ta.getstring (R.styleable.TopBar_ Lefttext); Mrighttextcolor = Ta.getcolor (R.styleable.topbar_righttextcolor,0); mrightbackground = Ta.getdrawable (r.styleable.topbar_rightbackground); mrighttext = Ta.getstring ( R.styleable.topbar_righttext); mtitletextsize = Ta.getdimension (R.styleable.topbar__titletextsize,Ten); Mtitletextcolor = Ta.getcolor (R.styleable.topbar__titletextcolor,0); mtitle = ta.getstring (R.styleable.topbar__title);//After getting the value of Typedarray, it is common to call the Recycle method to avoid re-creating errorsTa.recycle ();

It is important to note that when all the property values are obtained, you need to call Typedarray's Recycle method to complete the reclamation of the resource.

Combining controls

Next, we can begin to assemble the controls. UI Template Topbar actually consists of three controls, namely the left click Button Mleftbutton, the right click button Mrightbutton and the middle title bar Mtitleview. By adding the controls dynamically, use the AddView () method to add the three controls to the defined Topbar template, and give them the specific property values we obtained earlier, such as the caption color, size, and so on, as shown in the code below.

//Assign a value to the created component element//value is derived from the assignment of the corresponding attribute in the referenced XML fileMleftbutton.settextcolor (Mlefttextcolor); Mleftbutton.setbackground (Mleftbackground); MLeftButton.setText ( Mlefttext); Mrightbutton.settextcolor (Mrighttextcolor); Mrightbutton.setbackground (MRightBackground); Mrightbutton.settext (Mrighttext); Mtitleview.settext (Mtitle); Mtitleview.settextcolor (MTitleTextColor); Mtitleview.settextsize (mtitletextsize); mtitleview.setgravity (Gravity.center);//Set the appropriate layout element for the component elementMleftlayoutparams =NewLayoutparams (Layoutparams.wrap_content, layoutparams.match_parent); Mleftlayoutparams.addrule ( Relativelayout.align_parent_left, TRUE);//Add to ViewGroupAddView (Mleftbutton, mleftlayoutparams); mrightlayoutparams =NewLayoutparams (Layoutparams.wrap_content, layoutparams.match_parent); Mrightlayoutparams.addrule ( Relativelayout.align_parent_right, TRUE); AddView (Mrightbutton, mrightlayoutparams); mtitlelayoutparams =NewLayoutparams (Layoutparams.wrap_content, layoutparams.match_parent); Mtitlelayoutparams.addrule ( Relativelayout.center_in_parent, TRUE); AddView (Mtitleview, mtitlelayoutparams);

  · Defining interfaces
Define a button-click interface in the UI template class and create two methods for clicking on the left button and clicking on the right button, as shown in the code below.

// 接口对象,实现回调机制,在回调方法中// 通过映射的接口对象调用接口中的方法// 而不用去考虑如何实现,具体的实现由调用者去创建publicinterface topbarClickListener {    // 左按钮点击事件    void leftClick();    // 右按钮点击事件    void rightClick();}

  · Exposing the interface to the caller
In the template method, for the left and right buttons to increase the Click event, but not to implement the specific logic, but instead of invoking the appropriate click method in the interface, the code is as follows.

//button click event, no specific implementation required,//Just call the interface method, callback, there will be a specific implementationMrightbutton.setonclicklistener (NewOnclicklistener () {@Override     Public void OnClick(View v)    {Mlistener.rightclick (); }}); Mleftbutton.setonclicklistener (NewOnclicklistener () {@Override     Public void OnClick(View v)    {Mlistener.leftclick (); }});//Exposes a method to the caller to register an interface callback//interface to obtain the implementation of the interface method by the callback Public void Setontopbarclicklistener(Topbarclicklistener Mlistener) { This. Mlistener = Mlistener;}

  · Implementing interface Callbacks
In the caller's code, the caller needs to implement an interface, complete the method in the interface, determine the specific implementation logic, and use the method exposed in the second step to pass the object of the interface in order to complete the callback. Typically, the methods in the interface can be implemented using the form of an anonymous inner class, as shown in the code below.

mtopbar.setontopbarclicklistener ( New  Mytopbar.topbarclicklistener () { @Override  public  void  leftclick  () {Toast.makete XT (Mainactivity.    This , , Toast.length_short). Show (); }  @Override  public  void  rightclick  () {Toast.maketext (Mainactivity.this , " right ", Toast.length_short). Sh    ow (); }});

Here for a simple demonstration, only two toasts are displayed to distinguish between different button click events. In addition to implementing dynamic control UI templates in the form of interface callbacks, you can also use public methods to dynamically modify the UI in the UI template, which further improves the customization of the template, as shown in the code below.

/*** Set whether the button is displayed or not by the ID-sensitive button, flag distinguishes if it is displayed * * @param ID id* @param flag is displayed */ Public void setbuttonvisable(intIdBooleanFlag) {if(flag) {if(id = =0) {mleftbutton.setvisibility (view.visible); }Else{mrightbutton.setvisibility (view.visible); }    }Else{if(id = =0) {mleftbutton.setvisibility (view.gone); }Else{mrightbutton.setvisibility (View.gone); }    }}

With the code shown above, when the caller invokes this method through the Topbar object, the caller can dynamically control the display of the button according to the parameters, as shown in the code below.

// 控制topbar上组件的状态mTopBar.setButtonVisable(0true);mTopBar.setButtonVisable(1false);
Referencing UI Templates

The last step, naturally, is to refer to the UI template where it is needed, and before referencing it, you need to specify the namespace that references the third-party control. In the layout file, you can see the following line of code.

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

This line of code is in the specified namespace of the reference xmlns, which is XML namespace. This specifies that the namespace is "Android", so you can use "Android:" to refer to Android's system properties when using the System properties next. Similarly, if you want to use custom properties, you need to create your own namespaces, and in Android studio, third-party controls use the following code to introduce namespaces.

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

Here we will introduce the name space of the third-party control to the custom, and then use the custom attributes in the XML file, it can be referenced by this namespace, the code is as follows.

<cmj.com.delsys.mytopbar android:id=" @+id/topbar " android:layout_width=" match_parent " android:    Layout_height= "40DP"  custom:_title= "custom caption"  Custom:_titletextcolor= "#123412"  custom:_titletextsize=  "10sp"  custom:leftbackground= "@color/colorprimary"  custom:lefttext= "back"  custom:lefttextcolor= " #ffffff " custom:rightbackground=" @color/colorprimary " custom:righttext=< Span class= "hljs-string" > "more"  custom:righttextcolor= "#ffffff" /> 

The biggest difference between using a custom view and the system's native view is that when declaring the control, you need to specify the full package name, and when referencing the custom attribute, you need to use the custom xmlns name.
Further, if you write this UI template to a layout file, the code looks like this.

<cmj.com.delsys.mytopbar android:id="@+id/topbar"Xmlns:android="Http://schemas.android.com/apk/res/android"Xmlns:custom="Http://schemas.android.com/apk/res-auto"Android:layout_width="Match_parent"android:layout_height="40DP"custom:_title="Custom title"Custom:_titletextcolor="#123412"Custom:_titletextsize="10SP"Custom:leftbackground="@color/colorprimary"custom:lefttext="Back"Custom:lefttextcolor="#ffffff"Custom:rightbackground="@color/colorprimary"custom:righttext="More"Custom:righttextcolor="#ffffff"/>

With the code shown above, we can refer to the UI template view directly in the other layout file by tag, as shown in the code below.

<include layout="@layout/widget_topbar"/>

This makes our template requirements more satisfying.
After you run the program, the display effect appears as shown.




When the public method Setbuttonvisable () is called to control the display and hiding of the left and right two buttons, the effect appears as shown.



Project Address →mytopbar

Original address Custom View (ii) (Android Heroes)
My self-media blog Blankj Station, welcome to stroll.

Custom View (ii) (Android Heroes)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.