Step-by-step implementation of Android custom combination view

Source: Internet
Author: User
Tags event listener

Android Custom View Combination view

    • Android Custom View Combination view
      • Pre-order
      • Design Drawing UI Effects
      • Implementation ideas
      • Hands-on implementation
        • Inheriting LinearLayout implementing external outlines
        • Define the various required properties
        • Initialize view
        • Add some necessary interface methods
        • Custom View Completion
      • A reference to a custom view
      • Realize

Pre-order

Recently in the development of a e-commerce Class B-side app, relatively busy, now the latest version to go online. Just at the end of the year only to stop to comb the things you wrote, by the way to share some out, to give, but also please enlighten us.

Design Drawing UI Effects


What we're going to introduce here is the implementation of the UI effect behind three blocks. You can see that these blocks are similar, but if you want to write out a layout, not only the workload, but also cause the XML file code redundancy, file bloat. Obviously, we can achieve the effect of a block by customizing the view, and then include it in the place where it is needed, and the code is simple and good-looking.

Implementation ideas

The outermost layout uses linearlayout, and the picture section and the bottom text section can use Android:layout_weight to control the display scale. Text part can also use LinearLayout to layout, set android:gravity= "center" is good, inside of TextView don't repeat.

Hands-on implementation of inherited linearlayout for external contours

Write the XML layout file first, and adjust the effect you want to achieve. Here is the XML code:

<?xml version= "1.0" encoding= "Utf-8"?><linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"  Android:id="@+id/recommended_item_root"android:layout_width="Match_parent"  Android:layout_height="Match_parent"android:background="@drawable/item_bound"  android:orientation="vertical"android:clickable="true" >                             <com.personal.views.remoteimageview  android:id  =" @+id/recommended_item_front_cover " android:layout_width  = "match_parent"  android:layout_height  =" 0dip " android:layout_weight  = "2.5"  android:scaletype  =" Centercrop " android:src  =" @drawable/default_loading "/>     <linearlayout  android: Layout_width  = "match_parent"  android:layout_ Height  = "0dip"  android:layout_weight  =         "1"  android:gravity  = "center"  android:orientation  =;         <textview  android:id= "@+id/recommended_item_title"  android:layout_w Idth  = "match_parent"  android:layout_height
       = "wrap_content"  android:singleline  =
       
         "true" 
        android:ellipsize  =" end " android:gravity  =" center "            android:textcolor  = "@color/v123_light_gray"  android:textsize  = "15dip" />         <linearlayout  android:id  = "@+id/recommended_item_price_layout"  andro Id:layout_width  = "wrap_content"  android:layo Ut_height  = "wrap_content"  android:paddingbot  Tom  = "3dip"  android:orientation  = "horizontal" ;             <textview  android:id  = "@+id/recommended_item_newprice"  andro Id:layout_width  = "wrap_content"  android: Layout_height  = "wrap_content"  android:te Xtcolor  = "@color/red"  android:textsize
      = "15DP" />             <TextViewandroid:id="@+id/recommended_item_oldprice"android:layout_width ="Wrap_content"android:layout_height="Wrap_content"android:layout_ MarginLeft="15dip"android:textcolor="@color/v123_light_gray"android: TextSize="12DP" />                                                                                                        </linearlayout>    </linearlayout></linearlayout>

Create a new [java][6] code file Recommendeditem.java inherit LinearLayout, and use Layoutinflater to load the above layout file.

 Public  class recommendeditem extends linearlayout {     Public Static FinalString TAG = Recommendeditem. Class.getsimplename ();PrivateContext Mcontext;Private BooleanIsDataSet =false;Private floatTitletextsize, Newpricetextsize, oldpricetextsize;PrivateRemoteimageview Mitemcover;PrivateTextView Mitemtitle, Mitemnewprice, Mitemoldprice;PrivateLinearLayout Mpricelayout, Mrootlayout; Public Recommendeditem(Context context) {Super(context); Init (Context,NULL); } Public Recommendeditem(context context, AttributeSet attrs) {Super(context, attrs);    Init (context, attrs); }@SuppressLint("Newapi") Public Recommendeditem(context context, AttributeSet attrs,intDefstyle) {Super(Context, attrs, Defstyle);    Init (context, attrs); }Private void Init(context context, AttributeSet attrs)   {Mcontext = context; Layoutinflater.from (context). Inflate (R.layout.v2_recommended_item, This,true); }
Define the various required properties

Create a new Attrs.xml file under the Values folder and add the view properties we need.

<declare-styleable name="Recommendeditem">        <attr name="title_textsize" format="Dimension"/>        <attr name="newprice_textsize" format="Dimension"/>        <attr name="oldprice_textsize" format="Dimension"/> </declare-styleable>

Then we can refer to these properties in the XML file, and in the Init method of the Recommendeditem class, get the values of these properties that we write in the XML file.

TypedArray array = context.obtainstyledattributes (Attrs, R.styleable.recommendeditem); This. titletextsize = Array.getdimension (R.styleable.recommendeditem_title_textsize, the); This. newpricetextsize = Array.getdimension (R.styleable.recommendeditem_newprice_textsize, the); This. oldpricetextsize = Array.getdimension (R.styleable.recommendeditem_oldprice_textsize, A); Array.recycle ();//must be called, otherwise this setting will affect the next use.LOG.D (TAG,"This.titletextsize="+ This. titletextsize); LOG.D (TAG,"This.newpricetextsize="+ This. newpricetextsize); LOG.D (TAG,"This.oldpricetextsize="+ This. oldpricetextsize);
Initialize view
@Overrideprotected void onfinishinflate() {Super. Onfinishinflate (); This. Mitemcover = (Remoteimageview) This. Findviewbyid (R.id.recommended_item_front_cover); This. Mitemtitle = (TextView) This. Findviewbyid (R.id.recommended_item_title); This. Mitemnewprice = (TextView) This. Findviewbyid (R.id.recommended_item_newprice); This. Mitemoldprice = (TextView) This. Findviewbyid (R.id.recommended_item_oldprice); This. Mpricelayout = (linearlayout) This. Findviewbyid (R.id.recommended_item_price_layout); This. Mrootlayout = (linearlayout) This. Findviewbyid (R.id.recommended_item_root); This. Mitemtitle.settextsize ( This. titletextsize); This. Mitemnewprice.settextsize ( This. newpricetextsize); This. Mitemoldprice.settextsize ( This. oldpricetextsize);}
Add some necessary interface methods

The custom view provides an interface for external use and dynamically modifies its properties to achieve the desired display effect.

//Set Click event Listener Public void Setonclicklistener(Onclicklistener Listener) {if(Listener! =NULL) { This. Mrootlayout.setonclicklistener (listener); }} Public void Setitemcover(intRESID) { This. Mitemcover.setimageresource (resId);} Public void Setitemcover(String URL) { This. Mitemcover.setimageurl (URL);} Public void Setitemcover(Bitmap Bitmap,BooleanNeed2recycle) { This. Mitemcover.setimagebitmap (bitmap);if(need2recycle) {if(Bitmap! =NULL) {bitmap =NULL;        System.GC (); }    }} Public void Loaditemcover(String Remoteurl) {Uilmanager.displayimage (Remoteurl, This. Mitemcover, Uilmanager.optionspicspreview);} Public void Setitemtitle(String title) { This. Mitemtitle.settext (title);} PublicStringGetitemtitle() {if(! Textutils.isempty ( This. Mitemtitle.gettext ())) {return  This. Mitemtitle.gettext (). toString (); }return NULL;} Public void Setitemnewprice(String Newprice) { This. Mitemnewprice.settext (String.Format (mcontext.getstring (R.string.recommended_item_price_format), NewPrice));} Public void Setitemoldprice(String Oldprice) { This. Mitemoldprice.settext (String.Format (mcontext.getstring (R.string.recommended_item_price_format), oldPrice)); This. Mitemoldprice.getpaint (). SetFlags (Paint.strike_thru_text_flag);} Public void setpricelayoutvisible(BooleanVisible) {if(!visible) { This. mpricelayout.setvisibility (View.gone); }Else{ This. mpricelayout.setvisibility (view.visible); }} Public Boolean IsDataSet() {returnIsDataSet;} Public void Setdataset(BooleanIsDataSet) { This. IsDataSet = IsDataSet;if(IsDataSet && This. mpricelayout.getvisibility () = = View.gone) This. mpricelayout.setvisibility (view.visible);} Public void ClearView() { This. Mitemcover.setimageresource (r.drawable.default_loading); This. Mitemtitle.settext (NULL); This. mpricelayout.setvisibility (View.gone);}
Custom View Completion

At this point, we've completed our custom view based on the UI design diagram, and it's easy to use in any other layout file.

A reference to a custom view
<com.personal.views.RecommendedItem    android:id="@+id/recommended_spike_1"    android:layout_width="0dip"    android:layout_height="match_parent"    android:layout_marginLeft="10dip"    android:layout_weight="1" />
Realize

Step-by-step implementation of Android custom combination view

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.