Android (Java) Learning Note 204: Custom Smartimageview (inherited from ImageView, extended to automatically get network path pictures)

Source: Internet
Author: User

1. Sometimes the Android system Configuration UI control does not meet our needs, Android development to a certain extent, the number of the use of custom controls , on the one hand is more flexible, on the other hand, in the case of large data volume, the efficiency of the custom control is higher than the write layout file.

2. Below we are customizing a smartimageview inherited from ImageView, extending the functionality of ImageView :

Steps:

• Create a new Smartimageview class to inherit from ImageView (placed under a specific package);

The implementation of the construction method under the Smartimageview class, preferably all implemented, this is not prone to problems, while the subclass can not deprive the parent class construction method;

• Extended Function Method Setimageurl, by setting a network path to Smartimageview,smartimageview will automatically download the path corresponding to the image;

3. Let me illustrate with a specific case image:

(1) Create a new Android project, named " NetEase News Client _ Custom control (Smartimageview)", and a new class for Smartimageview Let it inherit from ImageView , here we do not have to ignore the layout files Activity_main.xml and Mainactivity.java;

Such as:

(2) Next we write Smartimageview, which expands the functionality of the ImageView:

1  PackageCom.himi.smart;2 3 ImportJava.io.InputStream;4 Importjava.net.HttpURLConnection;5 ImportJava.net.URL;6 7 ImportAndroid.content.Context;8 ImportAndroid.graphics.Bitmap;9 Importandroid.graphics.BitmapFactory;Ten ImportAndroid.os.Handler; One ImportAndroid.os.Message; A ImportAndroid.util.AttributeSet; - ImportAndroid.widget.ImageView; -  the /** - * Implement a subclass to extend the ImageView of the system -  * @authorAdministrator -  * +  */ -  Public classSmartimageviewextendsImageView { +      A     Private Static Final intSUCCESS = 1; at     PrivateHandler Handler =NewHandler () { -          Public voidhandlemessage (android.os.Message msg) { -             Switch(msg.what) { -              CaseSUCCESS: -Bitmap Bitmap =(Bitmap) msg.obj; - Setimagebitmap (bitmap); in                  Break; -  to             default: +                 //all other messages are failed to get the picture -                  Break; the             } *  $         };Panax Notoginseng     }; -  the      PublicSmartimageview (context context, AttributeSet attrs,intDefstyle) { +         Super(context, attrs, defstyle); A         //TODO Auto-generated constructor stub the     } +  -      PublicSmartimageview (Context context, AttributeSet attrs) { $         Super(context, attrs); $         //TODO Auto-generated constructor stub -     } -  the      PublicSmartimageview (Context context) { -         Super(context);Wuyi         //TODO Auto-generated constructor stub the     } -      Wu     /** - * Set the path of a network to Imageview,imageview will automatically download the path corresponding to the image. About      * @parampath of a path picture $      */ -  -      Public voidSetimageurl (FinalString Path) { -         NewThread () { A              Public voidrun () { +                 Try { theURL url =NewURL (path); -HttpURLConnection conn =(HttpURLConnection) url.openconnection (); $Conn.setconnecttimeout (5000); theConn.setreadtimeout (5000); theConn.setrequestmethod ("GET"); the                     intCode =Conn.getresponsecode (); the                     if(Code ==200) { -InputStream is = Conn.getinputstream ();//get the input stream of the picture file on the server side inBitmap Bitmap = Bitmapfactory.decodestream (IS);//convert the server-side picture file input into a bitmap image file the                         //Setimagebitmap (bitmap); the child thread cannot update the UI, which uses the message mechanism theMessage msg =Message.obtain (); AboutMsg.obj =bitmap; theMsg.what =SUCCESS; the handler.sendmessage (msg); the                     } +}Catch(Exception e) { - e.printstacktrace (); theHandler.sendemptymessage (0);Bayi                 } the              the                  -             }; - }.start (); the     } the      the}

Here we have said that we'd better implement all of the construction method, in the extension Method Setimageurl (): It is the use of Network path (String), to obtain the image resources on the network, where the use of network operations, it must be time-consuming operation, The Smartimageview we define will inevitably run in the main thread, and we know that the network operation cannot be placed on the main thread (UI main thread), so here a new child thread is created and the new thread () is combined with the handler (message mechanism) to implement the UI update.

(3) Next we go back to the Activity_main.xml layout file:

<Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Tools:context= "Com.himi.smart.MainActivity" >    <Com.himi.smart.SmartImageViewAndroid:id= "@+id/iv"Android:layout_centerhorizontal= "true"android:layout_centervertical= "true"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "@string/hello_world" /></Relativelayout>

Add a Smartimageview control that we define, set other parameters like ImageView (Smartimageview inherits from ImageView), and pay special attention here:

The start tag is " Package name + control class name ", for example here:

<com.himi.smart. Smartimageview

Android:id= "@+id/iv"

Android:layout_centerhorizontal= "true"

Android:layout_centervertical= "true"

Android:layout_width= "Wrap_content"

android:layout_height= "Wrap_content"

android:text= "@string/hello_world"/>

(4) The next natural is to use, back to Mainactivity.java:

 PackageCom.himi.smart;ImportCOM.HIMI.HEBAO.R;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.widget.ImageView; Public classMainactivityextendsActivity {PrivateSmartimageview IV; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); IV=(Smartimageview) Findviewbyid (R.ID.IV); Iv.setimageurl ("Http://a.hiphotos.baidu.com/image/pic/item/cf1b9d16fdfaaf51ebc1c2be8e5494eef01f7a94.jpg"); }}

Here the "Http://a.hiphotos.baidu.com/image/pic/item/cf1b9d16fdfaaf51ebc1c2be8e5494eef01f7a94.jpg" is the path of the network picture, As follows:

(5) Do not forget to add network permissions in Androidmanifest.xml: <uses-permission android:name= "Android.permission.INTERNET"/>

Deployment Program to simulator above:

Note: The Smartimageview written here is for the later Android (Java) Learning notes 205 NetEase News UI implementation of the extension class, the next chapter is detailed how to write a NetEase news client

Android (Java) Learning Note 204: Custom Smartimageview (inherited from ImageView, extended to automatically get network path pictures)

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.