1. Avoid edittext validation when entering a datewhen entering dates in EditText, it is often necessary to validate the dates entered, but we can use the button instead of EditText to avoid validation. first, replace the EditText control with the button control, but set the background of a EditText control to the button control so that it looks like a edittext control, as follows:
<button android:id= "@+id/details_date" android:layout_width= "match_parent" android:layout_ height= "Wrap_content" android:text= "Input date" android:textcolor= "@android: Color/holo_red_light" android:gravity= "center" android:background= "@android:d rawable/edit_text"/>
The @android:drawable/edit_text here is the background of the system, that is, the background of the edittext. and then implemented in Java code, when the user clicks on the control, a date selection dialog pops up, allowing the user to select the date directly instead of the input
private int myear; private int mmonth; private int mday; Private Ondatesetlistener Mdatesetlistener; Private Button Mdatebutton; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Get the current date final Calendar C = calendar.getinstance (); Myear = C.get (calendar.year); Mmonth = C.get (calendar.month); Mday = C.get (calendar.day_of_month); Mdatesetlistener = new Datepickerdialog.ondatesetlistener () {@Override public void Ondateset (DatePicker view, I NT year, int monthofyear, int dayofmonth) {Mdatebutton.settext (getString (R.string.picked_date_format, Monthofyear, DayOfMonth, year)); } }; mdatebutton= (Button) Findviewbyid (r.id.details_date); Mdatebutton.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Showdatepi Ckerdialog (); } }); } private void Showdatepickerdialog () {New DatepickerdIalog (This,mdatesetlistener,myear, Mmonth,mday). Show (); }
Summary: You may ask, why not set the Click event directly on the EditText and replace it with a button? Because using the button is more secure, users cannot modify the text display of the button. You can also use Textwatcher to verify the user's input, but this will take more time. Using Android's system resources in the app is a great way to take advantage of the original style of the device.
2. Formatted text display for TextView
The above tweet is made up of different text styles and colors: black, blue, and a part of the click to open a URL. It feels like a custom control to show this information, which is actually implemented with just one TextView control. The following example shows how to add different styles of text and hyperlinks to TextView. This is the XML layout:
<textview android:id= "@+id/hello_world" android:textsize= "18sp" android:layout_width= "Wrap_ Content " android:layout_height=" wrap_content " android:text=" Hello world! "/> <textview Android:id= "@+id/text_2" android:layout_width= "wrap_content" android:layout_height= "Wrap_content " Android:textsize= "18SP" android:layout_below= "@+id/hello_world" android:layout_margintop= "4DP " Android:text= "I feel like I'm going to drink some water, but your mouth is blocking my mouth." />
This is the Java code:
public class Mainactivity extends appcompatactivity {TextView helloworldtext; TextView Texttwo; String textlink= "Visit <a href=\" http://www.sina.com/\ ">sina home</a>"; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); The first to add a hyperlink helloworldtext= (TextView) Findviewbyid (R.id.hello_world); Helloworldtext.settext (html.fromhtml (Textlink)); Helloworldtext.setmovementmethod (Linkmovementmethod.getinstance ()); The second changes the foreground color and background color texttwo= (TextView) Findviewbyid (r.id.text_2); Spannable spannable=new spannablestring (Texttwo.gettext ()); Spannable.setspan (New Backgroundcolorspan (Color.Blue), 2,5,0);//Background Blue int index=texttwo.gettext (). toString (). IndexOf (",");//Gets the location of "," Spannable.setspan (New Foregroundcolorspan (Color.yellow), Index,texttwo.gettext (). Length () , 0);//foreground Yellow texttwo.settext (spannable); }}
The effect is as follows: Click Sina home to jump to Sina homepage
3. Add a glow effect to textAdd the LED effect as shown in the text.
First, create a new Ledtextview that inherits from TextView, which is used primarily to set font effects.
public class Ledtextview extends TextView { private static final String Fonts_folder = "FONTS"; private static final String font_digital_7 = Fonts_folder + file.separator + "Digital-7.ttf"; Public Ledtextview (Context context) { super (context); Init (context); } Public Ledtextview (context context, AttributeSet Attrs) { Super (context, attrs); Init (context); } Public Ledtextview (context context, AttributeSet attrs, int defstyle) { Super (context, attrs, defstyle); Init (context); } private void init (context context) { Assetmanager assets = context.getassets (); Final Typeface font = Typeface.createfromasset (assets,font_digital_7);//Set Font settypeface (font);} }
Then set two Ledtextview in the layout, one to display the background of the 88:88:88, one to display the current time, as follows:
<merge xmlns:android= "Http://schemas.android.com/apk/res/android" > < Com.manning.androidhacks.hack011.view.LedTextView android:layout_width= "wrap_content" android:layout_ height= "Wrap_content" android:layout_gravity= "center" android:text= "88:88:88" android:textcolor= "# 3300ff00 " android:textsize=" 80sp "/> <com.manning.androidhacks.hack011.view.ledtextview Android:id= "@+id/main_clock_time" android:layout_width= "wrap_content" android:layout_height= "Wrap_ Content " android:layout_gravity=" center " android:textcolor=" #00ff00 " android:textsize=" 80SP "/ ></merge>
Set in activity
public class Mainactivity extends Activity {private static final String Date_format = "%02d:%02d:%02d"; private static final int refresh_delay = 500; Private final Handler Mhandler = new Handler (); Private final Runnable Mtimerefresher = new Runnable () {@Override public void Run () {final Date d = new Date ( ); Mtextview.settext (String.Format (Date_format, D.gethours (), D.getminutes (), D.getseconds ())); Mhandler.postdelayed (this, refresh_delay); } }; Private TextView Mtextview; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Mtextview = (TextView) Findviewbyid (r.id.main_clock_time); } @Override protected void Onresume () {super.onresume (); Mhandler.post (Mtimerefresher); } @Override protected void OnStop () {super.onstop (); Mhandler.removecallbacks (Mtimerefresher); }}
Where%02d is used to limit the number format,2 is the width, if the integer is not enough 2 columns to fill 0,likeprintf ("%02d", 3);The result is,
if the number is greater than 2, there is no effect, such asprintf ("%02d", 1234);1234
4. Add a rounded background to the controlAdd a drawable background directly to the control it's okay.
<shape xmlns:android= "http://schemas.android.com/apk/res/android" android:shape= "Rectangle" > < Solid android:color= "#AAAAAA"/> <corners android:radius= "15DP"/></shape>
5. Get the height and width of the control in the OnCreate () methodIf you call the view's GetHeight () and GetWidth () methods directly in the OnCreate () method, only 0 is returned, that is, the height and width of the control are not obtained. Since the drawing process of the layout is divided into two steps, measure and layout, first measure the width and height of the layout and each of the controls, and then determine where each control is positioned in the layout. The control can get width and height in the second step, and layout occurs after the OnCreate () method call, so the width of the control cannot be obtained in the OnCreate () method. to solve this problem, you can use the view's post () method, which takes a runnable parameter and adds it to the message queue. This runnable method executes in the UI thread. The Java code is as follows:
public void OnCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.main); Mtextview = (TextView) Findviewbyid (r.id.main_clock_time); LOG.D ("CRX", "Before Post:textview.width=" +mtextview.getwidth () + ", textview.height=" +mtextview.getheight ()); Mtextview.post (New Runnable () { @Override public void Run () { log.d ("CRX", "after Post:textview.width=" + Mtextview.getwidth () + ", textview.height=" +mtextview.getheight ()); } );}
The result of the following output:
6.VideoViews and screen switchingThis section mainly shows how to let the video in the phone when the rotation of the automatic conversion of the layout of the screen first, you can let vidioviews occupy the entire screen, but not visible. Then set up a view control to place the video when the phone is upright. The android:configchanges= "Orientation" property is then set in the manifest file for the current activity so that the onconfigurationchanged () method is automatically called when the phone is rotated. Therefore, you can add the following code in the Onconfigurationchanged () method:
Switch (Getresources (). GetConfiguration (). Orientation) {//Judge the horizontal screen case Configuration.orientation_landscape: {//If it is a flat screen Mportraitcontent.setvisibility (View.gone);//Hide Vertical screen controls//settings Videoviews High and wide properties relativelayout.layoutparams params = n EW Relativelayout.layoutparams (layoutparams.match_parent, layoutparams.match_parent); Params.addrule (relativelayout.center_in_parent); Mvideoview.setlayoutparams (params); Break } Case Configuration.ORIENTATION_SQUARE:case Configuration.ORIENTATION_UNDEFINED:case configuration.orientation _portrait:default: {//Vertical screen mportraitcontent.setvisibility (view.visible);//Hide horizontal control int[] Locationarray = new int [2]; Mportraitposition.getlocationonscreen (Locationarray);//Get control high and wide//set video space high and wide relativelayout.layoutparams params = New Relativelayout.layoutparams (Mportraitposition.getwidth (), Mportraitposition.getheight ()); Params.leftmargin = locationarray[0]; Params.topmargin = locationarray[1];Mvideoview.setlayoutparams (params); Break } }
7. Remove background to increase activity start speedIn Android ADK, there is a tool called Hierarchy Viewer that can clearly see the level and complexity of the layout. (Note: The real-machine debugging may not be able to view, if you want to use the Hierarchy Viewer is best to use the simulator) if we create a default Android project, the layout code is as follows:
<merge xmlns:android= "Http://schemas.android.com/apk/res/android" > < Com.manning.androidhacks.hack011.view.LedTextView android:layout_width= "wrap_content" android:layout_ height= "Wrap_content" android:layout_gravity= "center" android:text= "88:88:88" android:textcolor= "# 3300ff00 " android:textsize=" 80sp "/> <com.manning.androidhacks.hack011.view.ledtextview Android:id= "@+id/main_clock_time" android:layout_width= "wrap_content" android:layout_height= "Wrap_ Content " android:layout_gravity=" center " android:textcolor=" #00ff00 " android:textsize=" 80SP "/ ></merge>
View the hierarchy diagram for this layout in the hierarchy viewer as follows:
The layout of the Actionbar accounted for a large part, in fact, our layout code does not, is the theme of the project, if the removal of Actionbar, will greatly simplify the layout of the hierarchical relationship we can add a my_ under the Res/values folder Theme.xml, customizing the theme Inside
<resources> <style name= "Theme.nobackground" parent= "Android:theme" > <item name= "Android: Windownotitle ">true</item> </style></resources>
After the title is removed, the layout-level relationships are as follows:
The visible level tree depth is also reduced by one layer, with fewer branches. It's a bit faster to start the app on the real machine.
We already know that there are linearlayout and Ledtextview in the layout, how do Dectorview and framelayout here explain it? Framelayout is created when the Setcontentview () method is executed, and Dectorview is the root node of the hierarchy tree. By default, Framelayout fills the entire screen and has a default background color. The Dectorview holds the entire screen background. If our UI background is customized, the device will still take the time to draw the default background by default. So if we make sure we don't use the default background, we can remove the default background, which can speed up the creation of the activity. The method of removing the default background is also simple, as long as you add an attribute to the Style property just as follows:
<resources> <style name= "Theme.nobackground" parent= "Android:theme" > <item name= "Android: Windownotitle ">true</item> <item name=" Android:windowbackground "> @null </item> < /style></resources>
8. Custom ToastThe toast location defaults to the bottom of the screen, but we can also make the toast appear in other locations. use toast.setgravity (int gravity, int xoffset, int yoffset) methods. For example:
Toast.setgravity (gravity.top| Gravity.left, 0, 0);
Make toast appear in the upper-left corner of the screen
Customizing a Toastwrite the toast layout in XML first, as follows:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:id= "@+id/toast_layout_ Root " android:orientation=" horizontal " android:layout_width=" fill_parent " android:layout_height=" Fill_parent " android:padding=" 8DP " android:background=" #DAAA " > <imageview android:src=" @ Drawable/droid " android:layout_width=" wrap_content " android:layout_height=" Wrap_content " android: layout_marginright= "8DP" /> <textview android:id= "@+id/text" android:layout_width= "Wrap_ Content " android:layout_height=" wrap_content " android:textcolor=" #FFF " /></linearlayout >
Then add the layout to the toast and display it in the Java code:
Layoutinflater inflater = Getlayoutinflater (); View layout = Inflater.inflate (R.layout.custom_toast, (ViewGroup) Findviewbyid (r.id.toast_layout_root)); TextView Text = (TextView) Layout.findviewbyid (R.id.text); Text.settext ("This is a custom toast"); Toast toast = new Toast (Getapplicationcontext ()); Toast.setgravity (gravity.center_vertical, 0, 0); Toast.setduration ( Toast.length_long); Toast.setview (layout); Toast.show ();
Chapter III Some tips on controls