Android programming tips (continuous)

Source: Internet
Author: User
Tags border image

Android programming tips (continuous)
First: Intent jump is generally used for Activity class, but if you want to jump in a non-activity class, the solution is to add mContext before startActivity (intent), that is, context, and finally mContext. startActivity (intent); in other words, all methods that call activity in non-activity classes will do this in the future. If not, do the following: (Activity) mContext.

Second: the problem that textview content in the gridview cannot be centered. You can set the number of items displayed in a row in the gridview, so it reserves a part of space for each item. If textview is used to fill the item and the textview attribute is wrap_content, because the content is small, it only occupies part of the allocated space, so no matter how to debug the attribute, it looks like a top grid display, so the solution is to set the textview width to marth_parent so that grity = "center" will have:-D. Third: only one control can be nested under the Scrollview. When multiple controls exist, you can set a Relativelayout in the Scrollview to solve the problem. Forth: Android SDK Content load is slow. Solution: There is a file in the path C: \ Documents and Settings \ computer name. android folder, delete this folder, and restart the simulator. A dialog box is displayed, indicating that you can select "NO" for "Welcome to Android Development ". Five: in multi-layer nesting, if there are too many layers, the visibilty of the explicit control is visible, but it is still invisible on the interface. The solution looks quite strange: replace multiple layout with relativelayout. Unknown reason Six: if some responses in the activity are based on the adapter data and the adapter is separated from the activity, the data cannot be returned to the activity (see the Listview and GridView reserved data interface for details). The solution is as follows: generally, the adapter is called by the activity and the activity listdata that needs to be passed in. Therefore, when we receive data, we can obtain the activity method as shown in the Code: QYSPActivity activty; // call the public QYSPFLInfoAdapter (activity Activity, List Listdata ){ Super (activity, 0, listdata); activty = (QYSPActivity) activity; // obtains the activity class} calls the activty method in the activity where needed. doPost (XXXXX); // doPost () is a defined method in the activity. Remember not to take the activity name when getting the name. Because the name is the same as that of the (QYSPActivity) activity, then the obtained activity method is null, and then the various error solutions change the name or this. activity = (QYSPActivity) activity; to put it bluntly, it is this. the statement cannot be hurt ~~ This method can be used for visual testing, but how can it be reversed... Seven: setContentView and inflate difference setContentView () once called, layout will immediately display the UI; while inflate will only form a ready-made object in the view class, if necessary, use setContentView (view) to display it. generally, the interface is displayed through setContentView () in the activity. However, if you want to set the control layout in a non-activity, LayoutInflater needs to be dynamically loaded. Eight: dynamically delete a listview item Nine: Use contentView + static ViewHolder class to optimize the adapter. When convertView = null is determined, if it is null, it will be based on the Item layout (XML) of the designed List ), to assign values to convertView, and generate a viewHolder to bind various View Controls in converView (those controls in XML layout ). Use the setTag of convertView to set viewHolder to the Tag, so that the system can retrieve it from the Tag when drawing the ListView for the second time. (See the code below) ViewHolder holder;
    if(convertView == null)            {                holder = new ViewHolder();                convertView = mInflater.inflate(R.layout.list_item, null);                holder.img = (ImageView)convertView.findViewById(R.id.img);                holder.title = (TextView)convertView.findViewById(R.id.title);                holder.info = (TextView)convertView.findViewById(R.id.info);                convertView.setTag(holder);            }else            {                holder = (ViewHolder)convertView.getTag();                holder.img.setImageResource(R.drawable.ic_launcher);                holder.title.setText("loulijun");                holder.info.setText("www.cnblogs.com/loulijun");            }
Eleven: the xml of a single control cannot be scaled down. In fact, no matter how many layout_width and layout_height values of the Button are modified, there will be no effect, because these two values have completely lost their role. We usually use layout_width and layout_height to set the size of the View, which always works normally, as if these two attributes are indeed used to set the size of the View. In fact, they are used to set the size of the View in the layout. That is to say, the View must first exist in a layout, after that, if layout_width is set to match_parent, the View width is filled with the layout. If it is set to wrap_content, the View width can just include its content, if it is set to a specific value, the View width is changed to a corresponding value. This is why these two attributes are called layout_width and layout_height, instead of width and height. Let's take a look at our button_layout.xml. Obviously, the Button control does not exist in any layout currently, so the layout_width and layout_height attributes certainly do not play any role. So how can we change the button size? There are actually many solutions. The simplest way is to nest a layer of layout outside the Button. Of course, the layout of the outermost layer is ineffective at this time. Ten: difference between throw and throws the throw statement is used in the method body to throw an exception. The statements in the method body process the throws statement after the method declaration, and then throw an exception, the statement in the upper-level method that calls this method to handle throws is mainly to declare that this method will throw this type of exception, so that the exception will be caught when it is called elsewhere. Throw is a specific action to throw an exception, so it throws an exception instance. Throws indicate the possibility of throw. If throw is preferred, you turn the tendency into true. At the same time: 1) throws appear in the method function header, while throw appears in the function body; 2) throws indicates a possibility of exceptions, which may not always occur. throw throws exceptions, and throws certain exceptions. 3) both are passive Exception Handling Methods (here the negative is not to say that this method is not good). It only throws or may throw an exception, but it is not handled by the function, the real exception handling is handled by the upper-layer call of the function. Twelve: gravity and layout_gravityandroid: gravity: For the view control itself, it is used to set the position where the view text should be displayed. The default value is left-side android: layout_gravity: relative to the parent element that contains the modified element, set the location of the element in the parent element. For LinearLayout, if android: orientation = "vertical" is set, android: the layout_gravity setting takes effect only in the horizontal direction. If android: orientation = "horizontal" is set, the android: layout_gravity attribute takes effect only in the vertical direction. Thirteen: the input box with the delete button and function * because we cannot directly set the click event for EditText, therefore, we use the place where we press it to simulate click events * When we press the position in the EditText width-the distance from the icon to the right of the control-the width of the icon and the * EditText width-icon even if we click the icon between the distance to the right of the control, it is critical to ignore these three lines in the vertical direction. The Code is as follows: boolean touchable = event. getX ()> (getWidth ()-getPaddingRight ()-mClearDrawable. getIntrinsicWidth () & (event. getX () <(getWidth ()-getPaddingRight (); // mClearDrawable is the delete button if (touchable) {this. setText ("");} Add the delete button in the input box Forteen: open failed: EISDIR (Is a directory) when creating a directory folder in the SD card, you should create a folder layer by layer, but you cannot create these two folders at a time. it is easy to create a specific file as an empty folder to be created. Create "/mnt/sdcard/zhufu/apkbus. db" as a folder, and an EISDIR error occurs. Solution: Create the folder first and create the final file. For example, File parentFile = new File (path); if (! ParentFile. exists () {parentFile. mkdirs ();} File file = new File (parentFile, filename + ". jpg "); // This is the final storage location. You must not repeat madirs here; otherwise, the above error will occur. 15: an I/O exception is reported when playing the same file MediaPlayer.
Solution: If you can play a video once, it means that the Player and the file are correct. However, if you play the video for the second time or report an IO exception, the reason is that the file to be played is in use, to play normally, the resource must be release before the Player can use it. Player. release ();. 16: The default initial position of the scrollview is on the top. Because there are other controls on the ListView in the scrollView, I think of a way to get the focus of one of the controls above at the beginning, the scroll bar naturally goes to the top, as shown below:

TxtBaseMsg. setFocusable (true );
TxtBaseMsg. setFocusableInTouchMode (true );
TxtBaseMsg. requestFocus (); control the sliding to the bottom: sv. fullScroll (ScrollView. FOCUS_DOWN ); 17: Notification dynamic icon
Generally, the icons of notification are static by default, but in some cases, the icons must be dynamic. The solution is actually quite simple, that is, to change the icon continuously for notification and then display it. Notif. iconLevel = 0; manager. interval y (0, notif); SystemClock. sleep (100); notif. iconLevel = 1; manager. interval y (0, notif ); 18: difference between getWidth and getMeasuredWidth getWidth (): the width of the entire View after the layout is set

GetMeasuredWidth (): The width occupied by the View content after the content on the View is measured. The premise is that you must call measure () in the onLayout () method of the parent layout or the onDraw () method of this View; (the value of the measure parameter can be defined by a friend ), otherwise, the result obtained is the same as that obtained by getWidth.

The main difference between the two methods is whether the measure () method is used, and the position used by measure () is also important.

The difference between getHeight () and get MeasuredHeight () is the same.

GeiHeight sometimes gets 0. The general reason is that this method is called before the View is fully drawn, So 0 is obtained. There are many ways to solve this problem, mainly to call these methods later. You can try to call these methods in onWindowFocusChanged. 19: When onItemClickListener is clicked to distinguish multiple listView or GridView items, the onItemClickListener interface of the system is generally called directly, but they cannot be distinguished and cannot get the id, v. getId can be distinguished, but the get of the parent can be used to distinguish, which is equivalent to the view of clickListener. 20: In the text below the image (code version) // get the image resource and size the last two sentences are to destroy the image to prevent OOM Bitmap = BitmapFactory. decodeResource (mContext. getResources (), R. drawable. icon_daohang_select); width = bitmap. getWidth (); height = bitmap. getHeight (); bitmap. recycle (); bitmap = null; Focus: holder. text1.setText (mTextList. get (position); Drawable d = mContext. getResources (). getDrawable (mImgList. get (position); d. setBounds (0, 0, width, height); holder. text1.setCompoundDrawables (null, d, null, null ); 21: Clever usage of android: onClick = "onClick" in xml
If xml is introduced elsewhere in the Code, the xml click event is a little troublesome, so you can use the method of the previous question, because this is the same as the onclick event that comes with android, therefore, you can directly apply the click method. (The other part is the same as the normal onclick event ).
  22: Set the navigation bar and status bar (only available for 4.4 or above). This is used to set the interface at the top of the app, that is, to set the battery information of the WiFi logo time: first, you must enable the transparent theme function of the activity. You can inherit the theme settings of the activity *. translucentDecor, set the theme attribute of android: windowTranslucentNavigation or android: windowTranslucentStatus to true, or enable the window identifier of FLAG_TRANSLUCENT_NAVIGATION or FLAG_TRANSLUCENT_STATUS in the activity code. Activation:
// Create a management instance for the status barSystemBarTintManager tintManager =NewSystemBarTintManager (This);// Activate the status bar settingsTintManager. setStatusBarTintEnabled (True);// Activate navigation bar settingsTintManager. setNavigationBarTintEnabled (True);

Set status bar color and Image

// Set a color for the system barTintManager. setTintColor (Color. parseColor ("# 99000FF "));// Set a style Background for the navigation barTintManager. setNavigationBarTintResource (R. drawable. my_tint );// Set a status bar ResourceTintManager. setStatusBarTintDrawable (MyDrawable );
23: Intent Flag is used in the Activity. The best way to clear all previous activities and tasks is to add a Flag FLAG_ACTIVITY_CLEAR_TASK to the Activity. The Flag is explained before the Activity is started, any tasks associated with this activity will be cleared. That is to say, this activity will become a new bottom activity in an empty stack, and all old activities will be finished. This identifier can only be used together with FLAG_ACTIVITY_NEW_TASK. Intent. addFlags (Intent. FLAG_ACTIVITY_CLEAR_TASK | Intent. FLAG_ACTIVITY_NEW_TASK );
If you want to retain two activities, that is, to retain two actions in the new Task, the best practice is to start two activities at A time. The specific operation is as follows: Intent intent = new Intent (this,. class); intent. addFlags (Intent. FLAG_ACTIVITY_CLEAR_TASK | Intent. FLAG_ACTIVITY_NEW_TASK); startActivity (intent); intent = new Intent (this, B. class); startActivity (intent); at this time, the system will jump directly to the B interface, and A will be placed at the bottom of the Task, and return to interface A from interface B.
  24: Get the position of the control in the screen getLocationOnScreen Calculate the x and y values of the view in the global coordinate system. (Note that the value is counted from the top of the screen, that is, the height of the notification bar is included) // obtain the absolute coordinates on the current screen


GetLocationInWindow, Calculate the x and y coordinates of the view's widnow value, // obtain the absolute coordinates in the entire window (not very understandable = ,)

GetLeft,GetTop,GetBottom,GetRight,This group is used to obtain coordinates relative to its father.

If the parameters output in the OnCreate () event of the Activity are all 0, these parameters can be obtained only after the UI control is fully loaded.

25: Use of android: ellipsize

If the content in EidtText and textview is too long, it will automatically wrap. android: ellipsize and android: singleine can be used to solve this problem, so that there is only one line.

EditText does not support marquee

The usage is as follows:

In xml

Android: ellipsize = "end" ellipsis at the end

Android: ellipsize = "start" ellipsis at the beginning

Android: ellipsize = "middle" ellipsis in the middle

Android: ellipsize = "marquee"

Android: singleline = "true"

You can also use code statements.

TV. setEllipsize (TextUtils. TruncateAt. valueOf ("END "));

TV. setEllipsize (TextUtils. TruncateAt. valueOf ("START "));

TV. setEllipsize (TextUtils. TruncateAt. valueOf ("MIDDLE "));

TV. setEllipsize (TextUtils. TruncateAt. valueOf ("MARQUEE "));

TV. setSingleLine (true );

26: edittext cursor in XML: Android: pidding = "10dp", you can move the cursor back a bit and set the cursor behind the font in the Code: titleView. setSelection (titleView. getText (). length (); () indicates the content length of the input box. 27: drawpidding and drawableLeft set the left (Up, down, left, right) border image of textview. The former is used to set the interval between text and drawable. 28: Chinese bold TextView TV = (TextView) findViewById (R. id. TextView01 );
TextPaint tp = TV. getPaint ();
Tp. setFakeBoldText (true); bold for others: Use android: textStyle = "bold" in xml files" 29: In a View, if you use a TAG to pass a value, for example, to add a click event to a dynamic View and obtain some values in the View, how can you pass the value to the past? TAG is used here. Click the event and write it as follows: view. setOnClickListener (new ContactClick (); the listener event can be implemented as follows: private class ContactClick implements OnClickListener {@ Overridepublic void onClick (View v) {}}, but in this case, the data in the View is not obtained, click events cannot be completed. So, use setTag and getTag to transmit messages. The Tag in View has two usage methods: 1. View. setTag (Object tag); the API is written as follows: Sets the tag associated with this view. A tag can be used to mark a view in its hierarchy and does not have to be unique within the hierarchy. tags can also be used to store data within a view without resorting to another data structure. set the labels associated with this view. A tag can be used to mark a view in a hierarchy without being unique. Tags can also be used to store data in a view, instead of accessing other data structures. (There is a problem with visual Translation in the second sentence) view. getTag () is used together with this function. API: the Object stored in this view as a tag. Returns an Object stored in the View with a tag. 2, View. setTag (int key, Objecttag) API: Sets a tag associated with this view and a key. A tag can be used to mark a view in its hierarchy and does not have to be unique within the hierarchy. tags can also be used to store data within a view without resorting to another data structure. the specified key shocould be an id declared in the resources of the application to ensure it is unique (see the ID resource type ). keys identified as belonging to the Android framework or not associated with any package will cause IllegalArgumentExceptionTo be thrown. Translation: Set a tag and a key associated with this view. Tags can be used to mark hierarchies that do not have to be unique in view hierarchies. Tags can also be used to store data in a view, instead of using other data structures. The key should be the application resource declared in the specified key id to ensure that it is unique (See ID resource type ). Keys is the key of the Android framework or any unrelated package. Otherwise, an IllegalArgumentException is thrown. (Translation is problematic) there is no difference in nature between the two. Both are pass-through values, but ① is generally only a leaflet value, and ② is used to pass multiple values. Note that this Key is used when multiple values are passed. It cannot be a common int type data. It requires the same id as other controls and cannot be repeated, the so solution is to create ids in the value. store ideg in the xml file: You can solve the problem by using R. id. tag_name during the call. The solution for the last full version is: // Add data view. setTag (R. id. tag_name, str1); view. setTag (R. id. tag_address, str2); // Add listener view3.setOnClickListener (new ContactClick (); // listener event private class ContactClick implements OnClickListener {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub // obtain the data String name = (String) v. getTag (R. id. tag_name); String address = (String) v. getTag (R. id. tag_address );}} 30: The textview text left cannot be set in the Code. Sometimes the TextView text direction cannot be set in the Code. The solution is LayoutParams params = new RelativeLayout. layoutParams (LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT); params. addRule (RelativeLayout. CENTER_VERTICAL); TV. setLayoutParams (params); TV. setGravity (Gravity. LEFT); reset the layout of TextView, and then set the text direction. 31: Listening to the Return key often overwrites the return key event. Generally, it overwrites the button and clicks the event, and then determines whether the return key is pressed or not. This is generally cumbersome and there is onBackPress () in android () method. Just rewrite it. 32: if you do not know the Map data and need to traverse the data in the Map, you need to traverse the Map by using the following method: Iterator it = levelMap. entrySet (). iterator (); while (it. hasNext () {// obtain the node Entry entry = (Entry) it. next (); // obtain the key valuesString key = (String) entry of the node. getKey (); String value = (String) entry. the getValue () ;}***** method is not unique over ~ 33: There are many methods to traverse the list and delete an item. Note: If you need to delete a node during the traversal, you cannot use the for () loop to delete the node, this problem occurs when you use for loop deletion. I deleted the node I = 5 (I = 6 after I ++ ), then, when I make the next judgment, I will directly interpret the value at I = 6 of the new list, but the length of the new list is-1, in addition, the content after I> 5 is moved one by one. I = 6 nodes ran to I = 5, but as shown above, I = 5 nodes are not judged, so error occurs. Solution: 1. Construct a list that is the same as the list to be traversed, an object to be traversed, and an object to be deleted. There is no problem if the two are separated, finally, assign the value of the deleted object to the object to be traversed. 2. Use Iterator to traverse data. You can use it. remove () to delete the data. (It. remove () can only be called once, and an exception is thrown multiple times) 3. Use for traversal. Whether Iterator or for () is used, the current item is deleted. We can see from the above that the node I = 6 is determined next time after I = 5 nodes are deleted, the original I = 6 nodes (I = 5 of the new list) are not judged. Can I be reduced by one after each node is deleted ?! The next judgment starts with I = 5, And I = 5 is just the previous I = 6, which avoids the problem of missed judgments, that's OK (this method is just an idea and has not been implemented yet, but it should be fine ). Over ~ 34: webView prohibit the copy and paste of Long press the selected paste text is the onLongClickListener function of webView. to disable the copy, you can intercept this event. This. appView. setOnLongClickListener (new View. OnLongClickListener (){
@ Override
Public boolean onLongClick (View view ){
Return true; // disables event return
}
}); 35: Anti-screenshot activity. getWindow (). addFlags (WindowManager. LayoutParams. FLAG_SECURE ); 36: the background is dimmed. WindowManager. LayoutParams lp = getWindow (). getAttributes (); lp. alpha = 0.3f; (smaller than 1) getWindow (). setAttributes (lp ); 37: screenshot capture and save activity. getWindow (). getDecorView (). setDrawingCacheEnabled (true); Bitmap bmp = activity. getWindow (). getDecorView (). getDrawingCache (); try {OutputStream out = new FileOutputStream (Filename); bmp. compress (Bitmap. compressFormat.. PNG, 100, out); out. close ();} catch (Exception e) {e. printStackTrace ();} 38: screenshots simulate clicking on android. Sometimes data and click events are encapsulated and triggered manually (such as the default homepage of pager). However, you cannot click in the program, in this case, you can use view. optional mclick (). Prerequisite: The view. onClickListener method sets the listener. NOTE: If view is used at the same time. the setOnTouchListener () method may intercept the view. performClick () RESPONSE event because when view. onTouchEvent () in event. getAction () = MotionEvent. when ACTION_DOWN is returned, false is returned. The system will think that the view does not need to process Touch events, and subsequent Touch events (move, up, and click) will not be passed in, so the view will not be triggered. when mclick (), and view. setOnTouchListener () is equivalent to overwriting the view. onTouchEvent (), so when writing the view's TouchListener processing, you need to pay attention to whether the view has a click event listener. If yes, use the view in the appropriate position. performClick () triggers a click event. 39: The clock controls include AnalogClock and DigitalClock, which are responsible for displaying the clock. The difference is that the AnalogClock control displays the analog clock and only the hour and minute hands, while the DigitalClock displays the digital clock, accurate to seconds. Both are directly added to the xml control. The time can be automatically displayed without java code control. 40: ExpandableListView expands all by default and click not to contract all expand: // expand all Groupprivate void expandELV (ExpandableListView elv, BaseExpandableListAdapter) {for (int I = 0; I <adapter. getGroupCount (); I ++) {elv. expandGroup (I) ;}/// block the group Click Event private void blockGroupClick (ExpandableListView elv) {elv. setOnGroupClickListener (new OnGroupClickListener () {public boolean onGroupClick (ExpandableListView parent, View v, int groupPosition, long id) {return true ;}});} 41: click "password visible hiding". In android, setTransformationMethod is provided for EditText to control the explicit hiding of the password. The main code is as follows:/* show the password */edittext. setTransformationMethod (HideReturnsTransformationMethod. getInstance ();/* hide the password */edittext. setTransformationMethod (PasswordTransformationMethod. getInstance (); or use InputType. // Display as common text pwdEdit. setInputType (InputType. TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); // display as a password
PwdEdit. setInputType (InputType. TYPE_CLASS_TEXT | InputType. TYPE_TEXT_VARIATION_PASSWORD ); 42: import custom properties xmlns: hyman = "http://schemas.android.com/apk/res-auto"

Related Article

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.