android.hacks.01_centering views using weights

Source: Internet
Author: User

Android.hacks Reading notes 01

  #1 # Analysis of weight layout:

LinearLayout ' s android:weightsum LinearLayout's child android:layout_weight

Compatible with the appropriate time, more convenient:

Defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of the children. This can is used for instance to give a single child 50% of the total available space by giving it a Layout_wei Ght of 0.5 and setting the WeightSum to 1.0.

   Simple Small Demo:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"Android:background= "#FFFFFF"android:gravity= "Center"android:orientation= "Horizontal"Android:weightsum= "1"><ButtonAndroid:layout_width= "0DP"Android:layout_height= "Wrap_content"Android:layout_weight= "0.5"Android:text= "click me"/></LinearLayout>

As for why the width of the button is set to 0DP, because, when the interface is drawn, the width is calculated according to the weight and then the width of the button, the actual width of the button is calculated, the formula is as follows:

Button ' s width + button ' s weight * 200/sum (weight)

Because the button ' s width is 0dp, the button's weight is 0.5. With the sum (weight)
Set to 1, the result would is the following: (assuming a screen width of 200)
0 + 0.5 * 200/1 = 100

Reference Link: http://developer.android.com/reference/android/view/View.html

  #2 # Avoid repeating some common layout, with <include> implementation

Relatively simple, small demo is as follows:

  

<Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"><TextViewAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"android:layout_centerinparent= "true"android:gravity= "Center_horizontal"Android:text= "@string/hello"/><includeLayout= "@layout/footer_with_layout_properties"/></relativelayout/>

And the footer_with_layout_properties would look like the following:

 <  textview  xmlns:android  = "http://schemas.android.com/apk/res/android"  android:layout_width  = "Fill_parent"   = "Wrap_content"   = "true"  android:layout_marginbottom  = "30DP"  android:gravity  = "Center_horizontal"  android:text  = "@string/footer_text"  />  

Note: If the parent layout is relative to the layout, and the <include> inside is a linear layout, then there is a possibility that the property will conflict, then put the layout_ of the <include> XML file. property, written in <include width: Height...>

can achieve the desired results.

#3 # Viewstub

  Associate the Viewstub class with the layout resource file specified in the XML file so that the layout resource file is loaded when it needs to be used. The main role is performance optimization, when to use when loading, not at the start of the time when the load, can speed up the program startup speed, but also save memory resources

Small Demo:

  

<Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent" >    <ButtonAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"android:layout_gravity= "Center_vertical"Android:onclick= "Onshowmap"Android:text= "@string/show_map" />    <viewstubAndroid:id= "@+id/map_stub"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"Android:inflatedid= "@+id/map_view"Android:layout= "@layout/map" />    <includeAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:layout_alignparentbottom= "true"Android:layout_marginbottom= "30DP"Layout= "@layout/footer" /></Relativelayout>

The layout is relatively simple, the optimization effect is not seen, if the layout is complex, then the optimization performance will be obvious.

#4 # Custom ViewGroup, and the use of preferencecategory

First, be familiar with viewgroup on screen display, draw the process, first execute Let's analyze the "the" to draw a viewgroup. The first step isto measure it width and height, and we do this in the onmeasure () method. Insidethat method, the ViewGroup would calculate its size by going through its children. We ' llMake the final pass in the OnLayout () method. Inside This second method, the view-Group would lay out it children using the information gathered in the onmeasure ()Pass.

Through 2 view tree traversal, the entire interface is drawn.

Custom controls see the source code.

--------------preferencecategory------The use of Android configuration interface, relatively simple and practical.

The Typedarray instance is a container for properties, and the Context.obtainstyledattributes () method returns. AttributeSet is a collection of properties for a node

Android.content.res.TypedArray

Contains obtainStyledAttributes(AttributeSet, int[], int, int) the function or obtainAttributes(AttributeSet, int[]) the retrieved array value.

Make sure that the call is done after the execution recycle()函数 . Used to retrieve values from this structure corresponding to the given property position to obtainstyledattributes.

Description of the functions involved:

obtainStyledAttributes(AttributeSet, int[], int, int)Or

obtainAttributes(AttributeSet, int[])

Defined:

Public TypedArray obtainstyledattributes (AttributeSet set, int[] attrs, int defstyleattr, int defstyleres) /c5>

Public TypedArray obtainattributes (AttributeSet set, int[] attrs) (description of this function)

Description: Returns a series of basic property values obtained by AttributeSet, without the need to perform a style with a theme or/and style resource.

Parameters:

Set: The value of the property retrieved now;

Attrs: The value of the property that was developed for retrieval

Public void Recycle()

Returns the previously retrieved array, which is later used.

/******************************************************************************* * Copyright (c) Manning * see The file license.txt for copying permission. /package Com.manning.androidhacks.hack004;import Android.content.intent;import Android.content.sharedpreferences;import Android.content.sharedpreferences.onsharedpreferencechangelistener;import Android.net.uri;import Android.os.bundle;import Android.preference.edittextpreference;import Android.preference.preference;import    Android.preference.preferenceactivity;public class Mainactivity extends Preferenceactivity implements Onsharedpreferencechangelistener {@Override public void onCreate (Bundle savedinstancestate) {super.oncreate (Savedin    Stancestate);    Addpreferencesfromresource (r.xml.prefs);    Preference sharepref = findpreference ("Pref_share");    Intent shareintent = new Intent ();    Shareintent.setaction (Intent.action_send); ShareinteNt.settype ("Text/plain");    Shareintent.putextra (Intent.extra_subject, "Check this app!");    Shareintent.putextra (Intent.extra_text, "Check This awesome apps at: ...");    Sharepref.setintent (shareintent);    Preference ratepref = findpreference ("Pref_rate");    Uri uri = uri.parse ("market://details?id=" + getpackagename ());    Intent gotomarket = new Intent (Intent.action_view, URI);    Ratepref.setintent (Gotomarket);  Updateusertext ();    } @Override protected void Onresume () {super.onresume ();  Getpreferencescreen (). Getsharedpreferences (). Registeronsharedpreferencechangelistener (this);    } @Override protected void OnPause () {super.onpause ();  Getpreferencescreen (). Getsharedpreferences (). Unregisteronsharedpreferencechangelistener (this); } @Override public void onsharedpreferencechanged (Sharedpreferences sharedpreferences, String key) {if (Key.eq    Uals ("Pref_username")) {Updateusertext ();  }} private void Updateusertext () {  Edittextpreference pref;    Pref = (edittextpreference) findpreference ("Pref_username");    String user = Pref.gettext ();    if (user = = null) {user = "?";  } pref.setsummary (String.Format ("Username:%s", user)); }}

<?xml version= "1.0" encoding= "Utf-8"?><!--Copyright (c) Manning see the file license.txt for copying Perm Ission.--><preferencescreen xmlns:android= "http://schemas.android.com/apk/res/android" android:key= "pref_        First_preferencescreen_key "android:title=" Preferences "> <preferencecategory android:title=" User "> <edittextpreference android:key= "Pref_username" android:summary= "Username:" Android        oid:title= "Username"/> </PreferenceCategory> <preferencecategory android:title= "Application" >            <preference android:key= "pref_rate" android:summary= "rate the app in the store!" Android:title= "Rate the app"/> <preference android:key= "Pref_share" android:summary= "Share the app with your friends" android:title= "Share it"/> <com.manning.androidhacks.hack004.pre Ference.           Emaildialog android:dialogicon= "@drawable/ic_launcher" android:dialogtitle= "Send Feedback" Android:dialogmessag            E= "does want to send a email with feedback?"             android:key= "Pref_sendemail_key" android:negativebuttontext= "Cancel" android:positivebuttontext= "OK" android:summary= "Send your feedback by e-mail" android:title= "Send Feedback"/> <com.ma Nning.androidhacks.hack004.preference.AboutDialog android:dialogicon= "@drawable/ic_launcher" Android :d ialogtitle= "About" android:key= "Pref_about_key" android:negativebuttontext= "@null" Android oid:title= "About"/> </PreferenceCategory></PreferenceScreen>

Detailed reference code see Android.hack, Series Source ==========================================================================

android.hacks.01_centering views using weights

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.