Android Custom Controls Create reusable combination controls _android

Source: Internet
Author: User
Tags getcolor

Has learned a custom control implementation, is Andriod custom control of the audio bar, has not learned the students can learn, the students have to study the next, must be fully mastered their own, and then continue to learn, can chew is not a good way to learn, We strive to learn a technology will be a technology, and not only look at the even, the best way is to read my own practice, and then expand, in the original based on the addition of something, for example, add some features to achieve, and so on.

Today we're going to learn another custom control, which is to create a reusable combination control, and the problem is:

What is reusable?
is that in the application, you can use a set of code in multiple places together. This will not only reduce our workload, but also to maintain the consistency of the application style, the most direct embodiment of this application is the uniform style of the title bar.

So what's the combo control again?
A composite control, as the name implies, is the combination of multiple controls that work together to accomplish certain functions.

Let's start our study with a unified title bar for app apps.

First of all, since it is a group of grouped controls, there must be a container that can contain these controls, and we have a lot of contacts that can hold controls, such as LinearLayout, Relativelayout, and many other layout, Today we choose Relativelayout to be our vessel. As before, we first define a Compositeviews class to inherit the Relativelayout class and rewrite its construction method as follows:

The public class Compositeviews extends relativelayout{

 the public compositeviews
  the context, the context, NULL);
 Public Compositeviews (context, AttributeSet attrs) {This
  (context, attrs,0);
 }
 Public Compositeviews (context, AttributeSet attrs, int defstyleattr) {
  Super (context, attrs, defstyleattr);
 }
 }

Next, we define three TextView controls, which are mlefetext,mrighttext,texttitle used to display "return", "Search" and "title" and to use Layoutparams to specify how they align within the container. Please look at the code:

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 {This
  (context,null);
 }
 Public Compositeviews (context, AttributeSet attrs) {This
  (context, attrs,0);
 }
 Public Compositeviews (context, AttributeSet attrs, int defstyleattr) {
  Super (context, attrs, defstyleattr) ;
  Initview (context);
 }

The Initview (context) method is used to initialize three grouped controls, see:

 private void Initview (context context) {Mlefetext = new TextView (context);
  Mrighttext = new TextView (context);
  Texttitle = new TextView (context);
  * * * Left button position * * Leftlayoutparams = new Layoutparams (layoutparams.wrap_content, layoutparams.wrap_content);
  Leftlayoutparams.addrule (relativelayout.align_parent_left,true);
  Mlefetext.settext ("return");
  Mlefetext.settextsize (22);
  /* Right button position * * Ridhtlayoutparams = new Layoutparams (layoutparams.wrap_content, layoutparams.wrap_content);
  Ridhtlayoutparams.addrule (relativelayout.align_parent_right,true);
  Mrighttext.settext ("search");
  Mrighttext.settextsize (22);
  * * Middle Heading position * * Titlelayoutparams = new Layoutparams (layoutparams.wrap_content, layoutparams.wrap_content);
  Titlelayoutparams.addrule (relativelayout.center_in_parent,true);
  Texttitle.settext ("This is a headline");
 Texttitle.settextsize (22); }

OK, the above code has implemented the display and alignment of the combined control, we add the defined view to the layout file and load it at the activity

Activity_main.xml file

<?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);
 }

Let's run the results first.

OK, it's been shown, but I'm sure you've seen it, in this code, the properties in each control are all fixed by us, and since we are creating a controllable control, it is certainly undesirable to fix the dead stuff, so how can we be flexible enough to get the properties of the control so that we can reuse it?

This has to be in touch with another technique, that is, a custom attribute. Our custom belongs to a property that can be assigned each time the control we define is used. Let's learn the custom properties below.

Custom attributes are actually quite simple, first of all, we now create a new Attrs.xml file under the resources file res under the values directory (Eclipse takes, as self-built), the new attrs.xml is a file containing the following code:

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

</resources>

There are a variety of properties in resources for us to use, students can see for themselves. Based on our current requirements, we chose to use declare-styleable to declare our attribute set, and then define a unique name attribute for it, which we can use to find all of the attributes in it when using the custom attribute. Please see the following code:

<?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>

Take a single line of attributes to resolve what it means:

OK, custom attributes we've finished learning, so how do we use our own defined attributes? It's also very simple to use our defined attributes directly in our Activity_main.xml file, but before you can use it, you must add the following line of code to the layout file by specifying the namespace for referencing the third party control:

Xmlns:custom= "Http://schemas.android.com/apk/res-auto"

Custom is the name of our third party namespace and can be arbitrarily named, and we must start with it when we use a custom attribute. Please look at the code:

 <?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 "cu
  Stom: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> 

We use custom to dynamically set property values, such as:/> @string, with the name values in the < attr name= "TitleText" format= "string" custom:titletext=. /titletext ".

OK, we've set the attribute values in our XML file, so how do we show them? This is to be acquired through a type group Typedarray, which contains various methods of obtaining properties from the AttributeSet attribute set, so we modify the above construction method and the Initview (context) method as follows:

 private void Initview (context context, AttributeSet attrs) {mlefetext = new TextView (context);
  Mrighttext = new TextView (context);

  Texttitle = new TextView (context);
  /** * Get custom Properties/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 ();
  * * * Left button position * * 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);
  /* Right button position * * 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);
  * * Middle Heading position * * 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);

 }

Code Explanation: First, we get the attributes into the Typedarray through the contextual context, then get the corresponding property values through various methods encapsulated in the Typedarray, and then set the properties for our control respectively. So it's done, the use of custom attributes, and the high reusability, whenever you need to use the title bar is only need to add our defined view control in the XML, for its configuration properties to use, save development time, improve efficiency, and also maintain the same app style.

Well, it feels like you've finished the whole process, but there's still one important realization that hasn't been said yet. Our controls can already be rendered, but how do we get the controls inside?

The common practice here is to use the callback mechanism to implement the development of the function, first we define an interface, create two methods for the left and right control of the Click event.

 public interface topbarclicklistener{
   void Leftclicklistener ();
   void Rightclicklistener ();
 }

You then add a click event for the left and right controls in the constructor, but do not implement the function, waiting for the caller to implement it themselves:

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 ();}}
  );
 

Furthermore, the defined interface is exposed to the caller:

 public void Setontopbarclicklistener (Topbarclicklistener topbarclicklistener) {
  Mtopbarclicklistener = Topbarclicklistener;
 }

Finally, who calls, who realizes. This completes the different interface multiplex control to realize the different function the convenience. Here we can only print toast in mainactivity.

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, "You clicked the Return key", Toast.length_short). Show ();
   @Override public
   void Rightclicklistener () {
    toastutil.maketext (mainactivity.this, "You clicked the Search key", Toast.length_short). Show ();}}

OK, let's see the results.

Good, already can realize our demand, is not to learn a lot of it.

Today, I mainly talked about the implementation of the Android custom view, and also learned the custom attributes, the students go down to digest, and hands-on reality one or two examples bar, well, today is about here, thank you.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.