Android Basics Getting Started tutorial--2.2.4 framelayout (frame layout)

Source: Internet
Author: User

Android Basics Getting Started tutorial--2.2.4 framelayout (frame layout)

tags (space delimited): Android Basics Getting Started Tutorial

Introduction to this section:

Framelayout (frame layout) is one of the simplest layouts in six layouts, a layout that opens directly on the screen
A blank area, when we add controls to it, they are placed in the upper-left corner of the area by default, and this layout
There is no positioning method, so it does not apply many scenes; the size of the frame layout is determined by the largest child control in the control, if the control
Size, you can only see the topmost component at the same time! The subsequent added controls will overwrite the previous one!
Although the control is placed in the upper-left corner by default, we can also assign it to a different location through the Layout_gravity Property!
This section in addition to show you a simple example, but also to bring you two fun examples, interested can see!

1. Common Properties

The properties of Framelayout are rarely two, but before we say it, we introduce one thing:
foreground Image: Always at the top of the frame layout, directly facing the user's image, is not overwritten by the picture
Two properties:
Android:foreground: Setting the foreground image of a frame-changing layout container
android:foregroundgravity: Setting the location of the foreground image display

2. Example Demo 1) The simplest example

Run:

The implementation code is as follows:

<framelayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  xmlns:tools  =" Http://schemas.android.com/tools " android:id  = "@+id/framelayout1"  android:layout_width  =" match_parent " android:layout_height  =" match_parent " tools:context  =". Mainactivity " android:foreground  =" @drawable /logo " android:foregroundgravity  =" right| Bottom ";         <TextViewandroid:layout_width= "200dp"android:layout_height=" 200DP "android:background=" #FF6143 " />                                            <TextViewandroid:layout_width="150DP"android:layout_height= "150DP" android:background="#7BFE00" />                                             <TextViewandroid:layout_width= "100dp"android:layout_height=" 100DP "android:background=" #FFFF00 " />                                        </framelayout>    

Code parsing:

Very simple, three TextView set different size and background color, then overlay, then the bottom right corner is the foreground image, through
android:foreground= "@drawable/logo" to set a picture of the foreground image
Android:foregroundgravity= "Right|bottom" to set the position of the foreground image in the lower right corner

2) The sister who moves with the finger

As follows:

Implement process resolution:

  • Step 1: Set the Main.xml layout to a blank framelayout and set a picture background for it
  • Step 2: Create a new Meziview custom component class that inherits the view class, initializing the initial coordinates of the view in the constructor method
  • Step 3: Override the OnDraw () method to instantiate an empty brush class paint
  • Step 4: Call Bitmapfactory.decoderesource () to generate a bitmap object
  • Step 5: Call Canvas.drawbitmap () to draw the sister's bitmap object
  • Step 6: Determine if the image is recycled, otherwise force the image to be recycled
  • Step 7: Get the Frame layout object in the main Java code and instantiate a Meziview class
  • Step 8: Add a touch event listener to the Mezi object that will be instantiated, override the Ontouch method, change the x, y coordinates of the Mezi, call invalidate () Redraw method
  • Step 9: Add the Mezi object to the frame layout

The implementation code is as follows:
Layout code:main_activity.xml

<framelayout xmlns:android="Http://schemas.android.com/apk/res/android"  Xmlns:tools="Http://schemas.android.com/tools"android:id="@+id/mylayout"  Android:layout_width="Match_parent"android:layout_height="Match_parent" Tools:context=". Mainactivity "android:background=" @drawable/back " >                                                    </framelayout>    

Custom Meziview.java

 PackageCom.jay.example.framelayoutdemo2;ImportAndroid.content.Context;ImportAndroid.graphics.Bitmap;ImportAndroid.graphics.BitmapFactory;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Paint;ImportAndroid.view.View; Public  class meziview extends View {      //define related variables, followed by the x, Y coordinates of the sister's display position     Public floatBITMAPX; Public floatBitmapy; Public Meziview(Context context) {Super(context);//Set the sister's starting coordinatesBITMAPX =0; Bitmapy = $; }//Override the OnDraw () method of the view class    @Override      protected void OnDraw(Canvas canvas) {Super. OnDraw (canvas);//Create, and instantiate the Paint objectPaint paint =NewPaint ();//Create a Bitmap object from a pictureBitmap Bitmap = Bitmapfactory.decoderesource ( This. Getresources (), r.drawable.s_jump);//Draw sisterCanvas.drawbitmap (Bitmap, bitmapx, bitmapy,paint);//Determine if the picture is recycled, and the wood is recycled to forcibly retract the picture        if(Bitmap.isrecycled ())          {bitmap.recycle (); }      } }

Mainactivity.java:

 PackageCom.jay.example.framelayoutdemo2;ImportAndroid.os.Bundle;ImportAndroid.view.MotionEvent;ImportAndroid.view.View;ImportAndroid.view.View.OnTouchListener;ImportAndroid.widget.FrameLayout;Importandroid.app.Activity; Public  class mainactivity extends Activity {      @Override      protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);          Setcontentview (R.layout.activity_main); Framelayout frame = (framelayout) Findviewbyid (r.id.mylayout);FinalMeziview Mezi =NewMeziview (mainactivity. This);//Add a touch event listener to our cute sisterMezi.setontouchlistener (NewOntouchlistener () {@Override               Public Boolean OnTouch(View view, Motionevent event) {//Set the location shown by SisterMEZI.BITMAPX = Event.getx ()- Max; Mezi.bitmapy = Event.gety ()- Max;//Call redraw methodMezi.invalidate ();return true;          }          });      Frame.addview (Mezi); }  }

Code Explanation:
See step, very simple, is to customize a view class, rewrite the redraw method, and then add a touch time to the activity
Override the Ontouch method in touch time to get the click Focus, plus 150, otherwise the coordinates are custom view
Upper left corner, then call invalidate () redraw method, and finally added to the frame layout!
Code Download: Http://pan.baidu.com/s/1pJJfKgz

3) The running of the cute sister

As follows:

Implementation process:

  • Step 1: Define an empty framelayout layout that sets the position of the foreground image to a central location
  • Step 2: Get the Framelayout layout in activity, create a new handler object, override the Handlermessage () method, call image-Update method
  • Step 3: Customize a Move () method to dynamically set the bitmap displayed by the foreground picture via switch
  • Step 4: Create a new Timer object in the OnCreate () method timer, override the Run method, and send empty information to handler every 170 milliseconds

The implementation code is as follows:

Layout file: Main_activity.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"        xmlns:tools="http://schemas.android.com/tools"        android:id="@+id/myframe"        android:layout_width="wrap_content"        android:layout_height="wrap_content"         android:foregroundGravity="center">    </FrameLayout>   

Mainactivity.java:

 PackageCom.jay.example.framelayoutdemo3;ImportJava.util.Timer;ImportJava.util.TimerTask;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.FrameLayout;Importandroid.app.Activity;Importandroid.graphics.drawable.Drawable; Public  class mainactivity extends Activity {        //Initialize variable, frame layoutFramelayout frame =NULL;//Customize a handler class object that is used to periodically update the UI interfaceHandler Handler =NewHandler () {inti =0;@Override                 Public void Handlemessage(Message msg) {//Determine if the information is issued for this application                if(Msg.what = =0x123) {i++; Move (i%8); }Super. Handlemessage (msg); }            };//define how to switch pictures when walking    voidMoveinti) {drawable a = Getresources (). getdrawable (R.drawable.s_1);            drawable B = getresources (). getdrawable (r.drawable.s_2);            drawable C = getresources (). getdrawable (R.drawable.s_3);            drawable d = getresources (). getdrawable (R.drawable.s_4);            drawable e = Getresources (). getdrawable (R.drawable.s_5);            drawable f = getresources (). getdrawable (R.drawable.s_6);            drawable g = getresources (). getdrawable (r.drawable.s_7); drawable h = getresources (). getdrawable (R.drawable.s_8);//Setforeground to set the foreground image        Switch(i) { Case 0: Frame.setforeground (a); Break; Case 1: Frame.setforeground (b); Break; Case 2: Frame.setforeground (c); Break; Case 3: Frame.setforeground (d); Break; Case 4: Frame.setforeground (e); Break; Case 5: Frame.setforeground (f); Break; Case 6: Frame.setforeground (g); Break; Case 7: Frame.setforeground (h); Break; }        }@Override        protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);            Setcontentview (R.layout.activity_main); frame = (framelayout) Findviewbyid (r.id.myframe);//Define a Timer object and send information to handler periodically        NewTimer (). Schedule (NewTimerTask () {@Override                 Public void Run() {//Send an empty message to notify the system to change the foreground pictureHandler.sendemptymessage (0x123); }            },0, the); }    }

Code parsing:
The code is also simple, which is to define a handler object to refresh the foreground image of the frame layout, define a timer timer
Timing information is sent every 170 milliseconds, i++;move (i%8); This is because we use 8 images as animated footage!
Code Download: Http://pan.baidu.com/s/1c0vL8PE

This section summarizes:

This section describes the next framelayout (frame layout), mastering the use of foreground and foregroundgravity properties!
The frame layout is a little bit more than the previous table layout! I would like to try to write a little example.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Basics Getting Started tutorial--2.2.4 framelayout (frame layout)

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.