Android development of those pits and tips

Source: Internet
Author: User

1, android:cliptopadding

This means that the drawing area of the control is inside the padding. The default is true. If you set the value of this property to False, you will be able to achieve a half-power effect on the layout. First look at one.

The top of the ListView in the default has a gap, and when you swipe up, the spacing disappears as shown in.

If you use margin or padding, you cannot achieve this effect. Adding a Headerview is overqualified and too troublesome. The cliptopadding with paddingtop effect is just right here.

2, Match_parent and Wrap_content

These two properties are supposed to be at a glance, one is to fill the layout space to accommodate the parent control, and one to accommodate its own content size. But if the list is in the ListView, the wrong problem is big. The GetView method in the ListView needs to calculate the list entry, it is necessary to determine the height of the ListView, Onmesure to do the measurement. If you specify a wrap_content, you tell the system, if I have 10,000 entries, you can help me calculate the display, and then the system according to your requirements to new 10,000 objects out. So you're not a tragedy? Look at a diagram first.

Assuming that the ListView now has 8 data, Match_parent needs a new 7 object, and Wrap_content needs 8. This involves the reuse of view, not much discussion. So the setting of these two properties will determine the number of GetView calls.

This extends another problem:GetView is called multiple times .

What is called multiple calls? For example position=0 it may have been called several times. It looks weird. Both the GridView and the ListView may appear, and perhaps the culprit is wrap_content. In the final analysis, there is a problem with the layout of the view. If the nested view is too complex, the solution can be the height required to measure the list through the code, or use a tip in GetView: Parent.getchildcount = = Position

@Override  Public View GetView (int  position, view Convertview, ViewGroup parent) {    if ( Parent.getchildcount () = = position)       {//  does thingshere    }             return convertview;   }
3, illegalargumentexception:pointerindex out of range

The scene of this bug is still very silent. At first I used Viewpager + PhotoView (an open source control) to display the picture, which was the problem when multi-touch zoom was zoomed out. At first I suspected that it was a photoview bug and found a half-day fruitless. It is not knowing how to try, always crash. Later only to know is the bug left by Android, the source code did not check pointer index. Re-compiling the source code is not likely. Knowingly have exception, and can not fundamentally solve, if not let it crash, it can only try-catch. The workaround is to customize a viewpager and inherit the Viewpager. Take a look at the following code:

/*** Custom Encapsulation Android.support.v4.view.ViewPager, overriding onintercepttouchevent events, capturing system-level exceptions*/ Public classCustomviewpagerextendsViewpager { PublicCustomviewpager (Context context) { This(Context,NULL); }     PublicCustomviewpager (Context context, AttributeSet attrs) {Super(context, attrs); } @Override Public Booleanonintercepttouchevent (motionevent ev) {Try {            return Super. onintercepttouchevent (EV); } Catch(IllegalArgumentException e) {LOGUTIL.E (e); } Catch(arrayindexoutofboundsexception e) {LOGUTIL.E (e); }        return false; }}

Replace the Viewpager layout file with the Customviewpager to be OK.

4, the item click event in the ListView is not responding

The item click event of the ListView suddenly does not respond, and the problem is typically when a button, checkbox, and other controls are added to the ListView. The problem is the focus of conflict. In Android, after tapping the screen, the click event will be assigned according to your layout, and when you add a button inside your listview, click the event first priority assigned to the button in your ListView. So your click item will expire, and you will need to set the Click event to the outermost layout of your item, or add a click event to one of your layout elements.

Workaround: Set in the root control of the ListView (the Joghen control is LinearLayout, add the following property setting in LinearLayout) Descendantfocusability property.

Android:descendantfocusability= "Blocksdescendants"

This is also the official document.

5, Getsupportfragmentmanager () and Getchildfragmentmanager ()

There is a requirement that fragment require nesting of 3 fragment. Basically can think of with viewpager realization. The start code is written like this:

Mviewpager.setadapter(New Customizefragmentpageradapter (Getactivity (). Getsupportfragmentmanager (), Subfragmentlist));

The problem that is caused is that nested fragment are sometimes inexplicably not displayed. At first you don't know where the problem is, and when you don't know the cause of the problem, it's obviously more of a hassle to solve it. After searching again and again, I finally saw the same question on the StackOverflow. Said to be with Getchildfragmentmanager () on it. It's so amazing!

Mviewpager.setadapter (new customizefragmentpageradapter (Getchildfragmentmanager, subfragmentlist));

Let's see what the difference is between the two. The first is the description of Getsupportfragmentmanager (or Getfragmentmanager):

Return the FragmentmanageR for interacting with fragments associatedwith this FR agment ' s activity.

Then the Getchildfragmentmanager:

Return a private fragmentmanager for placing and managing fragments insideof this F ragment.

Basically, the difference is so Fragment ' s now has their own internal fragmentmanager that can handle fragments. The child Fragmentmanager is the one, handles fragments contained within only the Fragment, it was added to. The other fragmentmanager is contained within the entire Activity.

It's quite clear.

6. ScrollView Nested listview

Isn't that a weird design? Two equally rolling view are put together, but also nested relationship. There was a need for this: the interface has a total of 4 regional parts, is the company's basic information (logo, name, legal person, address), company profile, company honors, corporate reputation list. Each part of the content needs to be based on the content of adaptive height, can not write dead. My first thought is also outside with a scrollview surrounded. The 4 sections are then encapsulated with 4 custom controls respectively. Basic information and company profile is relatively simple, honor needs to use the combination of Recyclerview and TextView, Recyclerview (of course, with the GridView can also, 3 rows of multi-row display) to store honor Pictures, TextView show honor name. The last part of the list of testimonials is of course the ListView. That's when the problem comes out. You need to solve the sliding problem and recyclerview display problem that the ListView puts into the ScrollView (if the height of the Recyclerview cannot be calculated, you cannot see the content).

Of course, there are already similar questions and solutions on the Internet.

To a Web site:

Four scenarios to solve ScrollView nested listview problems

The situation of the ListView is also better solved, the graceful approach is nothing more than writing a class to inherit the ListView, and then overriding the Onmeasure method.


protected void onmeasure (intint heightmeasurespec) { int expandspec = Measurespec.makemeasurespec (Integer.max_value >> 2, measurespec.at_most); Super . Onmeasure (Widthmeasurespec, Expandspec);}

The ListView can override the Onmeasure resolution, Recyclerview rewriting this method is not feasible.

In the final analysis of the height of the fact. There are two ways, one is to dynamically compute recycleview and then set up Setlayoutparams; the other is similar to the one that the ListView solves, Define a class to inherit Linearlayoutmanager or Gridlayoutmanager (note: not inherited Recyclerview), overriding the Onmeasure method (this method is troublesome, here is not table, next write an article to introduce).

The dynamic calculation height is as follows:

int heightpx = densityutil.dip2px (Getactivity (), (ImageHeight + imagerowheight) *new  Marginlayoutparams (Layoutparams.match_parent, HEIGHTPX); Mparams.setmargins (0, 0, 0, 0new Linearlayout.layoutparams (mparams); Honorimagerecyclerview.setlayoutparams (lparams);

The idea is this: After the server returns the honor picture, because is the 3 column display way, only need to calculate needs to display several lines, then given the line spacing and the picture height, then sets the setlayoutparams to be OK.

int lines = (int) Math.ceil (totalimages/3d);

At this point, this strange demand has been solved.

But in the sliding, feel the phenomenon of lag. Smart you must think of a sliding conflict. It should be scrollview sliding interference to the ListView. What do we do? Can you cut off the ScrollView slide?

Baidu, you can certainly search the answer. First on the code:

/** * @authorLeo * * Created in 2015-9-12 * intercept ScrollView sliding events*/ Public classCustomscrollviewextendsScrollView {Private intDownY; Private intTouchslop;  PublicCustomscrollview (Context context) { This(Context,NULL); }         PublicCustomscrollview (Context context, AttributeSet attrs) { This(context, Attrs, 0); }         PublicCustomscrollview (context context, AttributeSet attrs,intdefstyleattr) {        Super(context, attrs, defstyleattr); Touchslop=viewconfiguration.get (context). Getscaledtouchslop (); } @Override Public Booleanonintercepttouchevent (motionevent e) {intAction =e.getaction (); Switch(action) { CaseMotionEvent.ACTION_DOWN:downY= (int) E.getrawy ();  Break;  CaseMotionevent.action_move:intMovey = (int) E.getrawy (); if(Math.Abs (Movey-downy) >touchslop) {                return true; }        }        return Super. Onintercepttouchevent (e); }}

As long as the understanding of Getscaledtouchslop () This method is good to run. The comments for this method are: Distance in pixels a touch can wander before we think the user is scrolling. Say this is a distance, indicating that when the movement of the hand is greater than this distance to start the movement of the control, if less than this distance will not trigger the move.

It looks perfect.

But there is another problem: every time I load this interface takes too long, each time the interface is started by another interface, the card will be 1-2 seconds, and because of the phone performance time. Not because of a network request, fetching data is done by a child thread and has nothing to do with the UI thread. This kind of experience is very uncomfortable for you to see.

A few days passed, still like that. I'm going to show the boss right away. This experience is to be scolded 10 times.

Is it related to the nesting of ScrollView?

Well, then I refactor the code. No more scrollview. Use a ListView directly and add a Headerview to store other content. Because the control package is still good, did not change how much layout is OK, a run, smooth and slippery, all solved!

It is such a simple question, why do we have to use scrollview nesting?

StackOverflow already told you, do not nest like this! Don't nest like this! Don't nest like this! The important thing to say three times.

ListView inside ScrollView isn't scrolling on Android

Of course, starting with Android 5.0 Lollipop provides a new API to support embedded sliding, so the requirements like this can also be implemented well.

Here to a Web site, we are interested in self-understanding, not discussed here.

Android nestedscrolling Combat

7, Emojicontextview's SetText (null)

This is the TextView enhanced version of the open source emoticons library Com.rockerhieu.emojicon. I believe many people have used this open source toolkit. TextView with settext (null) is no problem at all. But Emojicontextview setText (null) after the tragedy, direct crash, showing the null pointer. At first I suspected that the view was not initialized, but not. Then debug it.

@Override  Public void SetText (charsequence text, Buffertype type) {    new  spannablestringbuilder (text);    Emojiconhandler.addemojis (GetContext (), builder, memojiconsize);     Super . SetText (builder, type);}

There seems to be nothing wrong with settext in Emojicontextview. Point Spannablestringbuilder go in and see, the source of the original is this:

/***  /Public Spannablestringbuilder (charsequence text)    {this (text, 0, Text.length ());}

All right. The problem has been found, text.length (), not empty pointers to blame.

null ? ""new spannablestringbuilder (text);

Add a line of judgment on the line.

8, Cursor.close ()

In general, database open and close will not be forgotten, but the use of cursors may not cause too much attention, especially the arbitrary use of cursors. For example, using Contentresolver with the cursor to query the SD card image, it is easy to write the following code:

null, MediaStore.Images.Media.MIME_TYPE + "=? or "                        new string[" {"Image/jpeg", "Image/png" },                        MediaStore.Images.Media.DATE_MODIFIED);  while (Cursor.movetonext ()) {    //  TODO     }

The cursor does not make a non-null judgment, and often does not pay attention to the possibility of exception throwing when the cursor is closed.

Previously in the project, often occur because the cursor did not close or close the exception is not handled to cause other problems, and the problem seems very strange, difficult to solve. Later, I reconstructed the use of cursors throughout the project, and there was no similar problem.

The principle is simple, and all cursor declarations are:

null;

and placed outside the Try-catch, need to use the cursor, first make a non-null judgment. Then at the end of the method, a tool class is used to handle the cursor closure.

/** * @authorLeo * * Created in 2015-9-15*/ Public classIoutil {PrivateIoutil () {} Public Static voidclosequietly (closeable closeable) {if(Closeable! =NULL) {            Try{closeable.close (); } Catch(Throwable e) {}}}  Public Static voidclosequietly (cursor cursor) {if(Cursor! =NULL) {            Try{cursor.close (); } Catch(Throwable e) {} }}}

I think that there is no need to try-catch-finally in every place.

Think of so much first, and then Add.

Reference:

Android:cliptopadding and Android:clipchildren

Howto:listview, Adapter, GetView and different list items ' layouts in one ListView

Android ListView calls GetView () cause analysis multiple times during initialization

Java.lang.IllegalArgumentException:pointerIndex out of range exception-dispatchtouchevent

What is difference between Getsupportfragmentmanager () and Getchildfragmentmanager ()?

Android development of those pits and tips

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.