Android Application Interface Development (III)

Source: Internet
Author: User

One, Inflater and custom controls

After the book, we now say inflater. Inflater is a tool that parses an XML file into a view in a Java file. It is equivalent to a larger Findviewbyid,findviewbyid is to find the control in the XML file, while Inflater is looking for the entire XML file to do the view.

Three ways to instantiate 1.Inflater

工欲善其事 its prerequisite, no matter what tool we use, the first step is to instantiate it.

 mLayoutInflater = getLayoutInflater(); mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); mLayoutInflater = LayoutInflater.from(MainActivity.this);

Does it look familiar? Yes, the last time we were talking about the ListView. Have used the second way to read a view. So, remember how we used him after the instantiation? Yes, we used a view-type view to get it using the Inflater method.

View view = inflater.inflate(R.layout.custom, null);

After that, we can use the name of the view. Findviewbyid to find the control to manipulate it. Such as:

EditText editText = (EditText)view.findViewById(R.id.content);
2. How to draw a control yourself

The way you customize controls is to inherit existing controls, layouts, or directly inherit view. Here's an example of inheriting view

1/Create a new control class and inherit the one you want to inherit
public   class  mylearn  extends  view  { public  mylearn  (Context context) {
    
     super  (context); } 
     public  
     mylearn  (context context, AttributeSet    Attrs) {
     super  (context, attrs); } 
     public  
     mylearn  (context context, AttributeSet Attrs, 
     int  defstyleattr) {
     super  (context, Attrs    , defstyleattr); }}
    

After inheritance, use shortcut keys to form their constructors directly, and then initialize them in each of them.
Of course, the small partners who have learned Java know that using this to invoke other constructs is a less re and more efficient method.

    publicTestRedButton(Context context) {thisnull);}    publicTestRedButton(Context context, AttributeSet attrs) {this0);}    publicTestRedButtonint defStyleAttr) {        super(context,attrs, defStyleAttr);        init(context,attrs);    }
2/Use OnDraw
    protected void OnDraw(Canvas canvas) {Super. OnDraw (canvas);//Make a circular red button        //Set the canvas to red        /** * Draw a red circle * *Mpaint.setcolor (Mbackgroundcolor); Canvas.drawcircle (GetWidth ()/2, GetHeight ()/2, getwidth ()/2, Mpaint);//getwidth () and GetHeight () are set property values, three parameters are position and radius, the last one is the canvas        //In the middle there is a white numberMpaint.setcolor (Color.White); Mpaint.settextsize ( $);/** * Mrect is the margin around this number */String Text = string.valueof (mnumber); Mpaint.gettextbounds (Text,0, Text.length (), mrect);intTextWidth = Mrect.width ();intTextHeight = Mrect.height (); Canvas.drawtext (text, getwidth ()/2-TextWidth/2, GetHeight ()/2+ TextHeight/2, Mpaint); }

In addition, because the OnDraw method will be used multiple times, it is best not to do a new operation in the OnDraw method. For example, as we wrote this time in Init,

privatevoidinit(Context context, AttributeSet attrs) {        new Paint();//设置一个画布        new Rect();        }
Expand 1/Set listener for custom controls

Add the following code to the Init method

this.setOnClickListener(new View.OnClickListener() {            @Override            publicvoidonClick(View v) {                    //你想要进行的一些操作                    invalidate();  // 刷新界面           }

Always remember to refresh the interface after the page changes.

Extension 2/new property (1) Create a new Attrs.xml file in the value folder (there is no need to create it) (2) write the following code in ATTRS:
<?xml version= "1.0" encoding= "Utf-8"?><resources>    <declare-styleable name="Testredbutton">        <attr name="backgroundcolor" format="Color"/>        <attr name="TextColor" format="Color"/>        <attr name="textSize"format="Dimension"/>       </declare-styleable></Resources>

The name of the eclare-styleable is the property of the corresponding control, where the name of the attr is the names of the properties, and format is the type of the property. In addition to the two above, there are many properties that can be used.

(3) Define and use in the Java file of the control

Add the following code to INIT, where attrs is provided by the constructor.

 TypedArray TypedArray = Context.obtainstyledattributes  (attrs, R.styleable  ) ;  The following is Eclare-styleable's name mbackgroundcolor = Typedarray.getcolor  (R.styleable   _backgroundcolor, Color)  eclare-styleable name plus attribute name and color mtextsize = Typedarray.getdimensionpixelsize  (R.styleable   _textsize, 18 ) ;  The name and size of the property  
Second, the use of fragment 1.Fragment understanding and role

Fragment is a templated activity file, which is part of the activity file. As we all know, we write code well, there is a very important standard, that is re rate. On many occasions there are many pages whose layout is similar to a large part. If each activity writes a corresponding layout file, it will make the whole file large and have many identical codes. But the two same activity layouts are only part of the same, not all of them, and there's no way to use different data transmissions or include. In this case, Android uses the fragment method, which allows us to extract the two similar parts of the activity with some of the same layout into a separate part, which is utilized in two activity, to reduce the re rate. In addition, Android runs on a wide variety of devices, with small screen phones, oversized flat panels, and even TVs. For the screen size gap, in many cases, the first to develop a set of apps for the mobile phone, and then copy, modify the layout to adapt to the plate God horse super large screen. Can't it be that an app can adapt to both the phone and the tablet, of course, must have. The appearance of fragment is to solve such problems. You can think of fragment as a part of an activity interface, even the activity of the interface can be completely different fragment composition, more handsome is fragment have their own life cycle and receive, handle the user's events, This eliminates the need to write a bunch of control's event-handling code in the activity. More importantly, you can dynamically add, replace, and remove a fragment.

Life cycle of 2.Fragment


Fragment must be dependent and activity, so the life cycle of activity can directly affect the life cycle of fragment. From here we can see a few more ways than Activity,fragment:

    • Onattach (activity): Called when fragment is associated with an activity.
    • Oncreateview (Layoutinflater, Viewgroup,bundle): Create a view of the fragment
    • Onactivitycreated (Bundle): Called when the activity's OnCreate method returns
    • Ondestoryview (): Corresponds to Oncreateview, called when the fragment view is removed
XML loading of 3.Fragment

The static use of fragment is actually very simple, add the fragment you want to call into the XML file. Of course, you have to have the view specified for it in the fragment file or in the main file. Well? No? Go up!
Or you just do it. Crisp

publiconCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        returnfalse);    }

By the way, put the notation in XML.

    <fragment        android:id="@+id/fragment_test"        android:name="com.132.Test01.TestFragment"        android:layout_width="match_parent"        android:layout_height="match_parent"        />

Name is your fragment class

4.Fragment Loading in Java 1/First of all we have two objects
        FragmentManager fragmentManager = getFragmentManager();        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
2/Create an instance of an object
        TestFragment testFragment = TestFragment.newInstance("我是极客班",15);
3/Add it to ViewGroup
        fragmentTransaction.add(R.id.fragment"test_fragment_tag");
4/Remove it
 fragmentTransaction.remove(testFragment);
5/Note that the above operation requires commit () before it takes effect 6/find it and operate after comparison
        Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_test);        fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {            @Override            publicvoidonBackStackChanged() {            }        });        ifinstanceof TestFragment){            // TODO: DO your action        else {            thrownew IllegalStateException("is not testFragment");        }
7/Common Other operations
    • Transaction.replace (): Replace the current with another fragment, which is actually the fit of remove () and then add () ~
    • Transaction.hide (): Hides the current fragment, is only set to invisible, and does not destroy
    • Transaction.show (): Show previously hidden fragment
    • Detach () Removes the view from the UI and differs from remove (), at which point the state of fragment is still maintained by Fragmentmanager.
    • The Attach () rebuilds the View view, attaches to the UI, and displays.
      Note: Common fragment buddies may often encounter such an activity state inconsistency: loss this error. The main reason is that the commit method must be called before Activity.onsaveinstance ().
Appendix: Back button click Method
    @Override    publicvoidonBackPressed() {        super.onBackPressed();    }
Appendix II: More Detailed fragment Introduction blog

Android Fragment Real full resolution (on) Android Fragment Real full parse (bottom)

Third, Handler's multi-threaded 1.handler understanding and why application

The small partners who have learned Java know that there is one thing in Java that is called threading, which is responsible for synchronizing all kinds of things with the main thread. The same is true for Android, where handler is responsible for primarily accepting data sent by child threads and updating the UI with this data in conjunction with the main thread. When the application starts, Android will first open a main thread (that is, the UI thread), the main thread is the UI controls in the management interface for event distribution, if you take a lot of time in this thread, it will cause the UI to die, more than five seconds after Android will be error, Forced shutdown is required. This time we need to put these time-consuming operations on a sub-thread, because the child threads involve UI updates, which will cause the Android main thread to be unsafe, that is, the update UI can only be updated in the main thread, and the operations in the child threads are dangerous. At this point we need to use handler to communicate between the main thread and the child thread, and put the new information into the main thread to update the UI.

Use of 2.handler

Handler need to be instantiated before they can be used, generally we do not recommend the use of internal classes for handler writing, because it will cause memory leaks. If the condition permits, write an external class separately for handler use.

1/message Mechanism Summary 1, instantiate Looper (because handler need a looper when instantiating), 2, instantiate handler, here need to overwrite Handlemessage method, processing received message, 3, instantiate Message object, By invoking the Obtainmessage method of the handler object that has been instantiated, the data is passed to the Obtainmessage method, and the Obtainmessage method instantiates a Message object. (You can also send an object that implements the Runnable interface); 4. Call handler's SendMessage method to send an instantiated message object. The wording of the 2/handler class
  class myhandler extends Handler {          PublicMyHandler () {} PublicMyHandler (Looper L) {Super(L); }//Subclasses must override this method to accept data@Override Public voidHandlemessage (Message msg) {//TODO auto-generated method stub            Super. Handlemessage (msg);Switch(Msg.what) Case...: Break;//Use what information here to Judge                 Case...: Break; }     }
Some methods of 3.handler
    • Post (Runnable): Run a thread
    • Postattime (Runnable,long): Run a thread at a time
    • Postdelayed (Runnable Long): Runs a thread after a few microseconds of stagnation
    • Sendemptymessage (int): Send an empty message
    • SendMessage (message): Send a message
    • Sendmessageattime (Message,long): Send a message at some point
    • Sendmessagedelayed (Message,long): How many seconds delay after sending a message
4. About Looper

The message queues and message loops of the Android system are for specific threads, a thread can exist (or can not exist) a message queue and a message loop (Looper), a message for a particular thread is only distributed to this thread, not cross-threading, and cross-process communication. However, the worker threads created by default have no message loops and message queues, and if you want the thread to have Message Queuing and message loops, you need to First call Looper.prepare () in the threads to create the message queue, and then call Looper.loop () to enter the message loop. More detailed looper analysis because there is no authorization, it is not written here.

5. Some good handler blog posts

Android handler details how to use an instance handler mechanism

Iv. introduction of the next issue

In the next issue, we will introduce services, broadcasts, and so on in Android.

Android Application Interface Development (III)

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.