Small knowledge points in Android-constantly updated

Source: Internet
Author: User

1. When you get an android resource image, for example, if you want to randomly get an image, you can put the ID of the image in a collection, but if there are too many images, this is still very troublesome. We can reflect the resource ID in the r file:

Public void onclick_randomface (view) {// random generation of an integer ranging from 1 to 9: int randomid = 1 + new random (). nextint (9); try {// randomly generated integers 1 to 9 from R. field object for obtaining the corresponding resource ID (static variable) in the drawable class field = R. drawable. class. getdeclaredfield ("face" + randomid); // obtain the resource id value, that is, the value of the static variable int resourceid = integer. parseint (field. get (null ). tostring (); // obtain the bitmap object bitmap = bitmapfactory of the resource Image Based on the Resource ID. decoderesource (getresources (), resourceid); // create the imagespan object imagespan = new imagespan (this, bitmap) based on the bitmap object; // create a spannablestring object, to insert the image spannablestring = new spannablestring ("face") encapsulated by the imagespan object; // replace face spannablestring with the imagespan object. setspan (imagespan, 0, 4, spannable. span_exclusive_exclusive); // append the randomly obtained image to the last edittext of the edittext control. append (spannablestring);} catch (exception e ){}}

In this method, the ID of any image resource in face1.pngto face9.png is randomly selected. The most common method is to put the nine image resource IDs in the array, and then randomly generate an array to attract the corresponding image resource ID.

2. Method 2: Obtain the resource ID using a string:

int resId = getResources().getIdentifier(getItem(position), "drawable", getPackageName());

The passed parameters are: String, directory, and package name.

3. nested gridview in the items of listview. The solution to the display of the gridview is incomplete:

Add the following code to the custom gridview:

public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);super.onMeasure(widthMeasureSpec, expandSpec);}

4. Solution for obtaining the getchildat method of listview as null:

Because listview. getchildat (lastposition) only applies to the view currently displayed. When a listview is dragged up or down, it will always refresh the view and load new data to clear the data that is not currently displayed, otherwise, when the listview data volume is too large, if an excessive amount of data is loaded at the same time, the consequences can be imagined.

Solution: Use the obtained position to subtract the position of the first visible item.

int po = position - listview.getFirstVisiblePosition();View mView = listview.getChildAt(po);

5. The R file is missing, and the fundamental solution

First, make sure your SDK is new.

Next, check your. xml file. The file name cannot be capitalized.

If there are too many XML files, clean your project and check the console prompts.

The console will prompt you where the XML file error is

After the XML file is modified

Clean your project, and then build your project

R. Java will reappear or be updated

6. Problem: Android bitmapfactory. decodestream, the bitmap returned by parsing is null

Cause: after checking the information on the Internet, I learned a bug in Android. When bitmapfactory. decodestream () is used in Android 2.2 or lower (including 2.2), an exception of probabilistic parsing failure occurs.

Solution:

1. Replace inputstream obtained from the network with byte

// Define a method for getting inputstream Based on the image URL public static byte [] getbytes (inputstream is) throws ioexception {bytearrayoutputstream outstream = new bytearrayoutputstream (); byte [] buffer = new byte [1024]; // use data to load int Len =-1; while (LEN = is. read (buffer ))! =-1) {outstream. Write (buffer, 0, Len);} outstream. Close (); // remember to close the stream. Return outstream. tobytearray ();} // use the decodebytearray () method to parse the encoding and generate a bitmap object. Byte [] DATA = getbytesfrominputstream (new URL (imgurl). openstream (); bitmap Bm = bitmapfactory. decodebytearray (data, 0, Data. Length );

2. If the file is a local file, use another parsing method.

BitmapFactory.decodeFile(file.getAbsolutePath(), opts);

6. Set custom title

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);setContentView(R.layout.main);getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

The layout can be customized in R. layout. Title (the above sequence cannot be reversed)

6. When the image is asynchronously loaded using the system asycntask
Causes and solutions for throwing a java. util. Concurrent. rejectedexecutionexception exception:

Http://www.gsdtarena.com/a/Androidjc/327.html

7. Get the width and height of the control in Android oncreate

When the oncreate function occurs, it only provides the opportunity for data initialization. At this time, the image has not been formally drawn. While the drawing is carried out in ondraw, the calculation is too late. One easy way to think of is to calculate the width and height of a specified control immediately or initialize the data after the program has just measured it. This requires a method to monitor the occurrence of this event. Fortunately, Android provides such a mechanism to use the getviewtreeobserver method in the View class to obtain the observer of the specified view, the callback is performed immediately before the control is drawn, so that the speed is not delayed and the data obtained is accurate. However, this method may be called repeatedly later, so you need to add restrictions, under normal requirements, only one calculation is enough. The Code is as follows (this code passes verification in the oncreate callback function, in real time, because it is a listener, so the event has nothing to do with oncreate ):

Layout = (metrolayout) findviewbyid (R. id. layout); viewtreeobserver VTO = layout. getviewtreeobserver (); VTO. addonpredrawlistener (New viewtreeobserver. onpredrawlistener () {public Boolean onpredraw () {If (hasmeasured = false) {int Height = metrolayout. getmeasuredheight (); int width = metrolayout. getmeasuredwidth (); // after obtaining the width and height, it can be used to calculate hasmeasured = true ;}return true ;}});

7. Usage of layoutparams in various layout modes of Android

Http://blog.sina.com.cn/s/blog_a2a3823601010hal.html

8. When running the program, the following exception is encountered, and the error is not very easy to find:

Android. content. res. resources $ notfoundexception: string resource ID #0x0

Later, it was found that

Holder. watchnum. settext (record. getlooknum ());

Record. getlooknum () returns the int type. An error occurred while setting it to a string. You only need to convert it to a string before setting it!

9. The edittext pop-up soft keyboard is squashed and the soft keyboard is disabled. Solution

To meet this requirement, there is an edittext, click the downward arrow on the input method, and when the input method is collapsed, dismiss edittext. The requirement is very simple. Android does not provide interfaces to collapse the listening input method! You can only add Android: windowsoftinputmode = "adjustresize" to the activity in an indirect way, and customize layout as the outermost layout, when the keyboard is collapsed, the custom Layout onsizechange and other methods will be called. This is equivalent to listening to the events collapsed by the input method... there is another condition that activity cannot be set to full screen!

It really sucks!

It's not the first time that we met this kind of thing that makes development quite sad. By the way, the classic 4.0 system cannot listen to the Home Key and how many coders have hurt the nerves.

The order of the system and the absence of broadcasting, and the priority can be set. As a result, the one-vote company sets the priority of the receiver to compete for the system's incoming call broadcast. It is not easy to say that the system design is poor or the development company has no lower limit, setpriority (integer. max_value. Only one sentence in the SDK documentation is "applications must use a value that is larger than system_low_priority and smaller than system_high_priority". If there is no limit, do you need to be conscious?

The introduction of fragment makes development much more flexible, and it makes developers feel a little more comfortable when adapting to machine types that are as versatile as cool. However, if you add fragment to development now, you will find that the workload not only does not decrease, but increases. You need to re-write a set of programs for machines less than 3.0 and more than 3.0. Well, not only do you write two sets of layout, but also two sets of code! This is another issue of version splitting. A major official version is available in a year, and the compatibility of new features is basically absent.

Http://blog.csdn.net/chang_xing/article/details/8105775

10. Get the status bar height in Android

/**     *      * @param activity     * @return > 0 success; <= 0 fail     */    public static int getStatusHeight(Activity activity){        int statusHeight = 0;        Rect localRect = new Rect();        activity.getWindow().getDecorView(        ).getWindowVisibleDisplayFrame(localRect);        statusHeight = localRect.top;        if (0 == statusHeight){            Class<?> localClass;            try {                localClass = Class.forName(            "com.android.internal.R$dimen");                Object localObject = localClass.newInstance();                int i5 = Integer.parseInt(              localClass.getField("status_bar_height").get(                localObject).toString());                statusHeight = activity.getResources(            ).getDimensionPixelSize(i5);            } catch (ClassNotFoundException e) {                e.printStackTrace();            } catch (IllegalAccessException e) {                e.printStackTrace();            } catch (InstantiationException e) {                e.printStackTrace();            } catch (NumberFormatException e) {                e.printStackTrace();            } catch (IllegalArgumentException e) {                e.printStackTrace();            } catch (SecurityException e) {                e.printStackTrace();            } catch (NoSuchFieldException e) {                e.printStackTrace();            }        }        return statusHeight;    }

11. Set Android: focusable = "false" and Android: focusableintouchmode = "false" in XML in imagebutton to grab the focus of listview, because such a bug exists in XML, you must set imagebutton in the code. setfocusable (false) takes effect

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.