Android ListView related issues (common interview)

Source: Internet
Author: User

Today, see a group of friends sent part of the interview questions, decided to write the answers to these questions, as follows:

1, how is the ListView compatible with ScrollView? Ok
2. Viewpager Unlimited Carousel Pictures
3. How to solve the memory overflow
4, Level three cache how to implement
5, how to save the user name password at login to achieve the next automatic login
6, if the SP only stores the user name, for example, three users are present in the SP, take out how to fetch? How do I save it? How do you differentiate
7, you log on only successful login and login failed? Is there no mechanism for re-interconnection? Broken network and then have a network back to the login interface how to login?
8, how to stay online status
9, Toobar,actionbar play the turn not?
10. Include tags always?
11, WebView Configuration Will it
12, Coordinatorlayout and Recycleview.
13, tab with Actionbar can be realized you know?
14. You know there's a button in the ListView. You know what, okay?
15, simple animation will you? Even when it comes to the presence and exit of activity.
16, the view of click Events and dialog Click event is easy to lead the wrong package
17, set list<> why dynamic growth? It has a default length, and sometimes he steps into an array of a specified length.
18. When downloading, the difference between the asynchronous task and the child thread
19, Recycleview instead of Listview,gridview, waterfall flow three modes switch freely
20, how to optimize the listview OK
21, fragment the difference between the two adapters
22, MVC,MVP
23, annotations? Findviewbyid
24. SOCKET,HTTP,XMPP,RSTP these Agreements
25. Oom Memory leak

Today decided to write the ListView related, I put the above 1, 14, 20 put together, that is, this article, the other later there is time to continue to update , if you are interested in this, please pay attention to me, we study together.

================================================

How is the ListView compatible with ScrollView?

We know that there are times when we need to nest a layer of scrollview in the ListView, with the following code:

    <ScrollViewandroid:id= "@+id/scrollview"android:layout_width=" Match_parent "android:layout_height=" Wrap_content ">                                <ListViewandroid:id="@+id/listview"android:layout_width="Match_ Parent "android:layout_height=" Wrap_content ">                                    </ListView>    </ScrollView>

As long as someone with a little bit of experience knows what's going to happen, yes, "ListView can't show normal entries, only show one or two", what's going on? this is because the ListView cannot correctly calculate its size in ScrollView, so it displays only one row.
As far as I know, the solutions to this problem are:

1. Method One: Rewrite the listview, overwrite the Onmeasure () method
Activity_list_view_scroll_view_test.xml:<merge xmlns:android="Http://schemas.android.com/apk/res/android"xmlns:tools="Http://schemas.android.com/tools"Android:layout_width="Match_parent"android:layout_height="Match_parent"Android:paddingbottom="@dimen/activity_vertical_margin"android:paddingleft="@dimen/activity_horizontal_margin"android:paddingright="@dimen/activity_horizontal_margin"android:paddingtop="@dimen/activity_vertical_margin"tools:context="Com.art.demo.ListViewScrollViewTestActivity"> <scrollview android:id="@+id/scrollview"Android:layout_width="Match_parent"android:layout_height="Wrap_content"> <com.art.demo.wrapperlistview android:id="@+id/listview"Android:layout_width="Match_parent"android:layout_height="Wrap_content"/> </scrollview></merge>wrapperlistview.java: Public  class wrapperlistview extends ListView {     PublicWrapperlistview (Context context) {Super(context); } PublicWrapperlistview (context context, AttributeSet Attrs) {Super(context, attrs); } PublicWrapperlistview (context context, AttributeSet attrs,intDEFSTYLEATTR) {Super(Context, attrs, defstyleattr); } PublicWrapperlistview (context context, AttributeSet attrs,intDefstyleattr,intDefstyleres) {Super(Context, Attrs, defstyleattr, defstyleres); }/** * Rewrite This method to achieve the effect of adapting the ListView to the ScrollView */    protected voidOnmeasure (intWidthmeasurespec,intHEIGHTMEASURESPEC) {intExpandspec = Measurespec.makemeasurespec (Integer.max_value >>2, measurespec.at_most);Super. Onmeasure (Widthmeasurespec, Expandspec); }}listviewscrollviewtestactivity.java: Public  class listviewscrollviewtestactivity extends appcompatactivity {    PrivateScrollView ScrollView;PrivateWrapperlistview ListView; @Overrideprotected voidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (r.layout.activity_list_view_scroll_view_test);        ScrollView = (ScrollView) Findviewbyid (R.id.scrollview);        ListView = (Wrapperlistview) Findviewbyid (R.id.listview);    Initlistveiw (); }Private voidInitlistveiw () {list<string> List =NewArraylist<> (); for(inti =0; I < -; i++) {List.add ("section"+ i +"Bar"); } listview.setadapter (NewArrayadapter<string> ( ThisAndroid.    R.layout.simple_list_item_1, list)); In addition, which big God can tell me in the code block (""), how to make a row bold, or do some other obvious mark??????????????????????????????????????
2. Method Two: Dynamically set the height of the ListView, do not need to rewrite the ListView

You only need to call the following method after Setadapter:

 Public void Setlistviewheightbasedonchildren(ListView ListView) {//Get ListView corresponding AdapterListAdapter listadapter = Listview.getadapter ();if(ListAdapter = =NULL) {return; }intTotalheight =0; for(inti =0, Len = Listadapter.getcount (); i < Len; i++) {//Listadapter.getcount () returns the number of data itemsView ListItem = Listadapter.getview (i,NULL, ListView);//Calculate the width height of the child viewListitem.measure (0,0);//Statistics total height of all childrenTotalheight + = Listitem.getmeasuredheight (); } viewgroup.layoutparamsparams= Listview.getlayoutparams ();params. Height = totalheight + (listview.getdividerheight () * (Listadapter.getcount ()-1));//Listview.getdividerheight () Gets the height of the delimiter between children        //Params.height finally get the entire ListView full display required heightListview.setlayoutparams (params); }

In addition, at this time, it is best to nest a layer of linearlayout outside the ListView, or sometimes this method will fail, as follows:

<merge  xmlns:android     = "http://schemas.android.com/apk/res/android"  xmlns:tools  = "Http://schemas.android.com/tools"     android:layout_width  = "match_parent"  android:layout_height  = "match_parent"  tools:context  = " Com.art.demo.ListViewScrollViewTestActivity ";     <ScrollViewandroid:id= "@+id/scrollview"android:layout_width=" Match_parent "android:layout_height=" Match_parent ">                                <linearlayoutandroid:layout_width="Match_parent"android:layout_ Height="Match_parent">                                    <ListViewandroid:id="@+id/listview"android:layout_width="Fill_ Parent "android:layout_height=" Match_parent "android:background=" #FFF4F4F4 "  android:dividerheight="0.0dip"android:fadingedge="vertical" / >                                                                                                        </linearlayout>    </ScrollView></Merge>
3. Method Three: In the XML file, directly to the height of the ListView to write dead

It can be determined that this way can change the height of the ListView, but there is a serious problem is that the ListView data can be changed, unless you can correctly write the height of the ListView, otherwise this way is a chicken.
As follows:

<ScrollViewandroid:id= "@+id/scrollview"android:layout_width=" Match_parent "android:layout_height=" Match_parent ">                                <linearlayoutandroid:layout_width="Match_parent"android:layout_ Height="Match_parent">                                    <ListViewandroid:id="@+id/listview"android:layout_width="Fill_ Parent "android:layout_height=" 300dip"android:background="#FFF4F4F4 " android:dividerheight="0.0dip"android:fadingedge="vertical" />                                                                                                         </linearlayout>    </ScrollView>
4. Method Four:

In some cases, in fact, we can completely avoid scrollview nested listview, such as using the ListView AddHeader () function to achieve the desired effect or use the layout features to achieve the desired effect, of course, how to use, only in the development of slowly pondering, Slowly summed up.

At this point, about the "ListView How and ScrollView compatible" This question is answered, if there is no understanding of the place can ask me, similarly, there are errors also welcome everyone pointed out, really appreciate.

The next thing to say is!!!!!.

How does the ListView optimize?

About the optimization of the ListView, as long as the interview people, I believe that the problem is very familiar with, whether or not someone asked you this question, I think you must have prepared, otherwise, hey!!!!! And a lot of searches on the internet. Here are just a few of the main:
1), Convertview Multiplexing, Convetview, when the Convertview is not empty, re-use, empty is initialized, thereby reducing the creation of a lot of unnecessary view
2) Define a viewholder, encapsulate all the components in the ListView item entry, set the Convetview tag to Viewholder, and not be empty when the corresponding component is obtained through the properties of the Viewholder
3), when the ListView load of large amount of data can be loaded with paging and picture asynchronous loading (about the ListView page load and picture asynchronous loading idea see the next article content)

Here are some related extensions to the ListView

1. Open the page layout with Listvew ScrollView The default starting position is not the top?

There are two ways to solve this problem:
Method One: Put the listvew in the inside not to get the focus. Listview.setfocusable (FALSE); Note: setting android:focusable= "false" in the XML layout does not take effect
Method Two: Myscrollview.smoothscrollto (0,0);

2. How does the pull-up and pull-down refreshes be implemented?

Implement the Onscrolllistener interface rewrite onscrollstatechanged and Onscroll methods,
Use the Onscroll method to implement a "swipe" post-processing check whether there are new records, if any, call Addfooterview, add records to adapter, adapter tune notifydatasetchanged Update data; Remove the custom Mfooterview. Use onscrollstatechanged to detect if you are rolling to the last line and stop scrolling and then perform the load

3. What does the ListView do with losing focus?

Write in the ListView sub-layout to solve the problem of lost focus
Android:descendantfocusability= "Blocksdescendants"

4. ListView Picture Asynchronous loading implementation ideas?

1. Get the picture display from the memory cache first (memory buffer)
2. Get the words from the SD card to get (SD card buffer, from the SD card to get the picture is placed in the sub-thread execution, otherwise the speed skating screen will not be fluent)
3. Can not get the words from the network download pictures and save to the SD card at the same time add memory and display (depending on the situation to see if you want to display)

5. You know, there's a button in the ListView, and you can't touch it, you know?

The reason is that the button forces the focus of the item, as long as the focusable of the button is set to False.

6. How to customize a adapter (interested can see, everybody don't throw my eggs)

Inherited from the Baseadapter implementation inside the method, the ListView at the beginning of the drawing, the system first called the GetCount () function, according to his return is worth to the length of the ListView, and then according to this length, call GetView () to draw each row. If your GetCount () return value is 0, the list will not show the same return 1, and only one row will be displayed. When the system displays the list, first instantiate an adapter (this will instantiate the custom adapter). When you manually complete the adaptation, you must manually map the data, which requires overriding the GetView () method. This method is called when the system draws each row of the list. GetView () has three parameters, position indicates that the first line will be displayed, Covertview is the layout inflate from the layout file. We use the Layoutinflater method to extract the well-defined Main.xml file into a view instance for display.
The individual components in the XML file are then instantiated (the Simple Findviewbyid () method). This allows the data to be mapped to individual components. However, in order to respond to a click event, the button needs to be added a click Listener to capture the click event. Now that a custom ListView has been completed, let's go back and look at the process from a new perspective. The system is going to draw the ListView,
He first gets the length of the list to draw, and then starts to draw the first line, how to draw it?
Call the GetView () function. In this function, we first get a view (actually a viewgroup) and then instantiate and set up each component to show it. Well, finish drawing this line. Then draw the next line until the painting is finished. During the actual run, you will find that each row in the ListView has no focus, because the button robs the ListView of the focus, as long as the button is set to no focus in the layout file.

7. What are the steps of the ListView page load?

There are usually two ways to implement page loading, one is to set a button at the bottom of the ListView and the user clicks to load. The other is automatically loaded when the user slides to the bottom.
A button is set at the bottom of the ListView and the user clicks the load implementation idea:

        //Add bottom view, note to be placed before the Setadapter methodListview.addfooterview (Moreview); Bt.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {pg.setvisibility (view.visible);//Make progress bar visibleBt.setvisibility (View.gone);//Button not visibleHandler.postdelayed (NewRunnable () {@Override                     Public void Run() {loadmoredate ();//Load more dataBt.setvisibility (view.visible);                        Pg.setvisibility (View.gone); Msimpleadapter.notifydatasetchanged ();//Notify ListView to Refresh Data}                }, -); }        });

When the user slides to the bottom, the implementation idea is automatically loaded:
Implement the Onscrolllistener interface override Onscrollstatechanged and Onscroll methods, use the Onscroll method to implement the "swipe" post-processing check if there are new records, if any, add records to adapter, Adapter calls notifydatasetchanged to update the data, and if there is no record, the data is no longer loaded. You can use onscrollstatechanged to detect if you are rolling to the last line and stop scrolling and then perform the load.

8. Does the viewholder inner class have to be declared static?

This is not an Android optimization, but a Java-promoted optimization,
If the declaring member class does not require access to the perimeter instance, always place the static modifier in its declaration, making it a static member class, not a non-static member class.
Because an instance of a non-static member class contains an additional reference to a perimeter object, saving the reference consumes time and space and causes the perimeter class instance to be persisted when it is eligible for garbage collection. If you need to assign an instance without a perimeter instance, you cannot use a non-static member class because an instance of a non-static member class must have a perimeter instance.

9. ListView Each item has effects into view 10. ScrollView, ListView Analysis-tensile rebound damping effect 11. Custom Controls-drop-down refreshes and pull-up loading of the ListView

================================================

There are several articles about the interview, interested in the small partners can go to my topic stroll, and all my Jane book articles directory here

For more information please follow my topic
Reprint please specify the original link:
http://www.jianshu.com/p/b7741023bc6f

Android ListView related issues (common interview)

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.