Android How to Customize View Properties _android

Source: Internet
Author: User

The example of this article introduced the Android custom view properties of the method for your reference, the specific contents are as follows

1. Customize one's own view class to inherit from view

public class MyView extends View
{public
  myview (context, AttributeSet attrs)
  {
    Super (context, ATTRS);
    Gets to the custom property
    TypedArray ta=context.obtainstyledattributes (attrs, r.styleable.myview);
    int Color=ta.getcolor (R.styleable.myview_rect_color, 0xffff0000);
    SetBackgroundColor (color);
    You must manually recycle TA
    ta.recycle ();
  }

  Public MyView
  {
    super (context);
  }
}

2. Create a new Attrs.xml file in the Res/values directory

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
  //define a declare-styleable tag, set attr attribute inside
  <declare-styleable name= "MyView" >
    <attr name= "rect_color" format= "color"/>
  </ Declare-styleable>
</resources>

A attr property that corresponds to a view property

3. Finally look at the layout file how to use the custom view we created and set its properties

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"
  /Customize a MyView namespace
  xmlns:gu = "Http://schemas.android.com/apk/res/com.gu.myrect"
  xmlns:tools= "Http://schemas.android.com/tools
  " Android:layout_width= "Match_parent"
  android:layout_height= "match_parent"
  android:orientation= "vertical" ">

  <com.gu.myrect.myview
    android:layout_width=" 100DP "
    android:layout_height=" 100DP "
    // Custom attribute values
    gu:rect_color= "#cc99cc"/> </LinearLayout> based on custom namespaces and the properties we set in Attrs

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.