The first line of code in chapter 4 mainly introduces the use of common controls and common layout.

Thinking: since the plan to try to write blog, as the development of small white at the beginning of the content can only be transported books, and these basic trivial knowledge points in the official documents and other books are everywhere, then I record these things how much meaning? How to be more than a book porter is the problem I face as a new developer and blogger.

Based on the control

For the base control, only its name and its more specific Settings are recorded.

Control common property

  • android.layout_width
  • android.layout_height
  • android.id
  • android.visibility: Can be set to VISIBLE/INVISIBLE/GONE

TextView

  • android.textSetting text content
  • android.gravityText alignment (top left alignment by default)
  • android.textColorThe font color
  • android.textSizeThe font size

Button

  • android.textAllCapsSet whether the buttons are in uppercase
  • addonClickListener: Set ButtonsetOnClickListenerOr inheritanceView.onClickListenerInterface and implement functionsonClick

EditText

  • android.hintSet the suggestive text
  • android.maxLineSets the maximum number of lines to be displayed
  • Get the contents of text:editTextView.text.toString(), using Kotlin syntax sugar simplificationgetText()function

It is found in practice that it cannot be implementedonClick()The function implementation listens because there are no corresponding annotations

ImageView

  • android.srcSpecify the picture to display
  • Change dynamically through codeImageViewIn the image: imageView. SetImageResource (newResource)

ProcessBar

  • android.styleAdjust the status of progress bars
  • Set the progress display:android.maxSet total progress + PassprogressBarView.progressSet current Progress

AlertDialog

AlterDialog can bring up a dialog box on the current interface and mask other interactive controls. It is generally used for warning or prompting. In addition, this View is set up in the Activity code and is typically used in response to certain interactions.

Three basic layouts

A layout is a container for placing various Spaces. It inherits from the UI classes View and ViewGroup, and can also be nested inside a layout.

LinearLayout

Aligns all controls in a linear direction

  • android.orientationTo set the direction of the arrangement, pay attention to the width and height Settings of the internal control

Settings for internal controls

  • android.layout_gravitySets the alignment of internal controls in the layout
  • android.layout_weightThe diao of this internal control through the form of proportion

RelativeLayout

Allow the control to appear anywhere in the layout by relative positioning.

Internal control Settings:

  1. Relative to the upper View
  • android.alignParentTop
  • android.alignParentBottom
  • android.alignParentLeft
  • android.alignParentRight
  • android.centerInParent

2, relative to other internal controls

  • android.layout_above
  • android.layout_below
  • android.layout_toLeftOf
  • android.layout_toRightOf
  • android.layout_alignLeft
  • android.layout_alignRight
  • android.layout_alignTop
  • android.layout_alignBottom

FrameLayout

The controls are placed in the top left corner by default and can be placed via Android.layout_gravity

Custom control

  • Reduce repetitive code by introducing common spatial layouts by introducing layouts. (include)
  1. Create layouts, such as title bar layoutstitle.xml. Place a set of controls in the layout.
  2. Introduce the layout in the main Layout. Add code<include layout="@layout/title" />
  • Create custom control, write event registration code separately, reduce the repetition of logic code.
  1. Create a new layout class TitleLayout and inherit LinearLayout
  2. The TitleLayout class dynamically loads the layout r.layout. title during initialization by init{LayoutInflater}, that is, the title bar layout in method one that has no listening set
  3. Add the TitleLayout control to the main Layout.
  4. Add a listener to the control in the TitleLayout class. (Use context as Activity to get control of the Activity)

The complex control

Next, we introduce two complex controls for scrolling that contain child controls inside.

ListView

ListView is a control used to slide data, but the data in the collection cannot be directly transferred to it. It needs to be completed with the help of an adapter. The following uses ArrayAdapter as an example to show the process of customizing ListView.

  1. Define the entity class to be displayed:Fruit
  2. Fruit_item.xml
  3. Create a custom adapterFruitAdapterAnd inherits from the parent classArrayAdapter, the rewritegetView()By means ofLayoutInflaterGet control of the fruit_item layout and bind the controls and resources in the layout using FruitList and position.
  4. Initialize the FruitList and FruitAdapter in the Activity code, and then set the Adapter of the ListView to FruitAdapter.

ListView efficiency optimization

  1. useconvertViewIn the functiongetView()To avoid using LayoutInflaters multiple times, you can reuse previously loaded cache layouts
  2. Custom inner classesinner class ViewHolderUsed to cache internal control instancesviewHolderStored in theview.tagAnd use ofviewHolderOperates on internal controls to reducefindViewById()The call.

ListView click event

  • useListView.setOnItemClickListener()Method and four parameters{parent, view, position, id}Perform operations.

RecyclerView

Compared with ListView, RecyclerView can realize more flexible multi-direction sliding display, and the operation efficiency is improved through the built-in viewHolder, and the control logic is clearer.

RecyclerView basic use process

  1. Add a dependency to your project’s build.gradle
  2. Add controls to the main Layout<androidx.recyclerview.widget.RecyclerView>
  3. Prepare the adapter for RecyclerView, create a new classFruitAdapterAnd he had inherited fromRecyclerView.Adapter
  4. Initialize data in MainActivity, specify layoutManager for recyclerView to determine the sliding mode, create and specify adapter for recyclerView.

Adapter

In my opinion, Adapter is to specify a child control or layout item for the sliding control RecyclerView, and add configuration to the control in the item, such as listener, and then improve the operation efficiency through ViewHolder and other ways.

  1. In the adapter classFruitAdapterCustom inner class ininner class viewHolderAnd inheritanceRecyclerView.ViewHolder, for storageitemIn the control
  2. inonCreateViewHolderTo load the child layout via LayoutInlfateritemAnd then throughitemViewInitialize theViewHolder
  3. inonBindViewHolderTo load the data from the List into a child control of the item based on the holder and position.

LayoutManager

In RecyclerView, by specifying Layoutmanager to specify the arrangement of the layout. Commonly used built-in layout have LinearLayoutManager GridLayoutManager, StaggeredGridLayoutManager.

RecyclerView click events

In RecyclerView, the click registration event of the View needs to be customized, that is, in Adapter onCreateViewHolder(), after the viewHolder is initialized, Listenre is set through the viewHolder child control.

The priority of listener

from StackOverFlow: Only one listener work at a time, the deeptest child get the priority over it’s parents.

Compare ListView and RecyclerView

ListView RecyclerView
Front rely on There is no Need to be
Layout management Its management LayoutManager
Loading layout Rewrite the getView () Rewrite onCreateViewHolder ()
Controls access to findViewById() viewHolder.targetView
Click on the event listView.setItemListener() viewHolder.button.setOnClickListener

Analysis of best practices

In the actual combat to create a similar wechat chat dialog box, so how to dynamically load two items in a RecyclerView layout has become the main problem. Solution steps:

  1. In the base classMsgSet constants inTYPEUsed to specify the type of message RECEIVED/SENT.
  2. Adapters in RecyclerViewMsgAdapterCreate two ViewHolder for caching controls in the left_item.xml and right_item.xml layouts, respectively.
  3. rewritegetItemViewType(position: Int)Function, returnsmsgList[positon]The TYPE of Msg
  4. inonCreateViewHolder()According to the functionviewTypeCreate the correspondingViewHolder
  5. inonBindViewHolderAccording to theholderType (LeftViewHolder/RightViewHolder) and Msg set of internal controls.