Android can’t get away with that





Android_Note

Here are some of the potholes that OcN. Yang encountered in the early stages of Android, and some of the development tips. I believe that most beginners will inevitably encounter the same pit, we probably have a look to avoid, haven’t encountered on the hide. Daniel and advanced friends can take a detour (I believe you are very busy).

This post was first posted on my personal blog site www.ocnyang.com

The original address

1. Shortcut key Ctrl + O

Look at the code outline, the list of methods for the class.

2, layout_weight

  • Once the View has this property set (assuming it is valid), the width of the View is equal to the original width (Android :layout_width) plus the remaining space!
  • If width is set to match_parent, then it adds a negative length (equivalent to subtracting some length).
  • If width is set to warp_content, then the remaining space is “total parent container length” minus “component content length” and then divided by the weight value.

3, Background @ = “null”

You can set a null value to the background, which may be necessary in some cases.

4. Check whether String is empty

TextUtils.isEmpty(String str)Copy the code

5, Int/ Int is still equal to an integer.

6. Orientation & Gravity in LinearLayout

When setting orientation=”vertical” in the LinearLayout:

  • If the child component setting layout_gravity=”center_vertical” is invalid;
  • Gravity =”center_vertical” on the LinearLayout will work to center the child components vertically. Same horizontal layout

Activity in single-instance mode

An Activity in singleInstance mode will have a separate task stack to hold the Activity, which will only be eliminated when the program exits.

8. Select the image from your phone and display it in ImageView

Intent intent = new Intent(); Intent.settype ("image/*"); Intent.action_get_content (intent.action_get_content); intent.action_get_content (intent.action_get_content); intent.action_get_content (intent.action_get_content); / / startActivityForResult(intent, 1); @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { Uri uri = data.getData(); ContentResolver cr = this.getContentResolver(); try { Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); ImageView imageView = (ImageView) findViewById(R.id.iv01); /* Set the Bitmap to ImageView */ imageView.setimageBitMap (Bitmap); } catch (FileNotFoundException e) { Log.e("Exception", e.getMessage(),e); } } super.onActivityResult(requestCode, resultCode, data); }Copy the code

NotifyDataSetChanged () updates Adaper.

10, ListView optimization

Main methods:

  1. ListView sets a fixed height,
  2. ConvertView sentenced to empty,
  3. SetTag: convertView SetTag (viewHolder),
  4. Inner class ViewHolder,
  5. Paging load

11, R file compilation error & can not find ID error

How R files are compiled: If one of the resource files or ID names does not meet the specification, R files as a whole are not compiled.

Check the CheckBox in the list





Note: Spinner: If the item has a control that can get focus (such as a CheckBox), it is passed to the control that can get focus after the item gets the click event. To retract the Spinner after the item is clicked, add the property to the layout (e.g. LinearLayout) to see if the descendant gets focus:

Android: descendantFocusability = "blocksDescendants" / / stop offspring gains focusCopy the code

Get the array defined in the XML resource file

getResources().getStringArray(R.array.city)Copy the code

14, Android default font size:





15. The Java string split has many holes

Java code

System.out.println(":ab:cd:ef::".split(":").length); / / separator at the end of all ignore System. Out. The println (" : ab: CD: ef: : ". The split (" : ", 1). Length); Println (stringutils.split (":ab: CD :ef::",":").length); system.out.println (stringutils.split (":ab: CD :ef::",":").length); / / the front and at the end of the separator all ignore, apache Commons System. Out. The println (StringUtils. SplitPreserveAllTokens (" : ab: CD: ef: : ", ":"). The length). Apache Commons output: 4, 6, 3, 6Copy the code

Public String[] split(String regex,int limit) {} public String[] split(String regex,int limit) {} For example, “o”split(“o”,5) or “o”split(“o”,-2) results in “” “”, as shown in the red box below. Therefore, split(String regex) method is usually used, which is the same as split(String regex, 0) method, discard the empty string at the end!





16. Global variables and strong keys for Android Studio

  • Findviewbyid(R.id.xx).cast After strong turn, hit Enter to return to the end of the line
  • .field global variable
  • .var Local variable

17, TextView add scroll bar





18. Array adapters





////xListView swipe refresh, slide load more ///swapListView swipe delete /

19, Viewstub

You can only inflatay once. Otherwise, an error will be reported.

20. Calculation method of rotation center of tween animation

Using the upper left corner of the image as the coordinate (0,0), calculate the values of pivotX and pivotY respectively: 50% is half of the size of the image itself, and 50%p is half of the width and height of the parent window. Then add these two arrays to the top left corner of the image





The displacement is calculated in the same way

21, plug-in

ButterKnife Gosn android.selector.generat

Margin & padding

Margin and padding in Android controls do not affect the width and height of the controls. (This is different from web design)

R file error.

When the layout or ID report cannot find an error, it may be an R file error.

  • One possibility is that you imported a incorrectly named resource file, causing the R file to not compile automatically.
  • One possibility is that you imported an R file from the android.R system, causing an error

ListView multiple types of items

In a custom ListView, if an item has multiple types of layout. So subscripts in getItemType must start at 0. Otherwise a subscript out-of-bounds exception will be reported.

25. How does Java intercept a regular expression field in a string

public static void main(String[] args) {
    String str = "<div><h3 ..>dsijiswer*dfhjgf</h3></div><table><h3>sdsd</h3></table>";
    Pattern p = Pattern.compile("<h3.*?/h3>");
    Matcher m = p.matcher(str);
    while (m.find()) {
        System.out.println(m.group());
    }
}Copy the code

Event mechanism: distribution consumption elevator mechanism: up distribution, down consumption

27, The interval between the internal child controls of the LinearLayout is set to be equal

Create a shape graphic file in the drawer folder

<? The XML version = "1.0" encoding = "utf-8"? > <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <size android:width="15dp" /> <solid android:color="@android:color/transparent" /> </shape>Copy the code

Set the divider attribute to the top graph in the linearLayout and the ShowDivider attribute

28, TextView to set the picture size method:

txtZQD = (TextView) findViewById(R.id.txtZQD); Drawable[] drawable = txtZQD.getCompoundDrawables(); Drawable [1]. SetBounds (100, 0, 200, 200); drawable[1]. txtZQD.setCompoundDrawables(drawable[0], drawable[1], drawable[2],drawable[3]);Copy the code

Understanding and path acquisition of internal and external storage in Android





30. Custom composite controls

You use the view.inflate (context, r.layout.img_share,this) when loading the layout; Or LayoutInflater. The from (context). Inflate (R.l ayout. Img_share, this); Can’t use LayoutInflater. The from (context). Inflate (R.l ayout. Img_share, null); It won’t load that way.

31. Foreground view comes into effect





Error when adding a third-party dependency





The configuration error cause is as follows: 1. The packet guide is incorrect. 2, less guide package. 3, repeat guide package.

33, layout in the ListView | the GridView preempted focus

The Scrollview has a nested Gridview, and the Gridview has a focal point problem (always display the layout from the first item of the Gridview)

Solution: After you get the inflate View, give the code to gridView.setfocusable (false)

So here we have a gridView of scrollView sliding horizontally nested inside the ListView item,

Same problem, same solution: set setFocusable(false) on the GridView after loading the item in the Adapter of the ListView. It is important to note that the list is set to unfocus after the parent container is created for the focused list.

For example: in a nested GridView within a ListView:

convertView = LayoutInflater.from(mContext).inflate(R.layout.item_listview_home, null);
viewHolder = new ViewHolder(convertView);
viewHolder.mGridIilh.setFocusable(false);Copy the code

There is a list in the Fragment layout to grab focus:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_cheapsale, null);
    ButterKnife.inject(this, view);
    mGridFragmentCheapsale.setFocusable(false);Copy the code

There is a list in the Activity layout to grab focus:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sale);
    ButterKnife.inject(this);
    mListviewHome.setFocusable(false);Copy the code

34. Lists grab focus

The first item is selected and gets the focus when the GridView and ListView initialize data or when we display notifyDataSetChanged. Android4.4 comments out the touchMode code when calling notifyDataSetChanged, resulting in notifyDataSetChanged simulating the user clicking on the GridView. We inherit the GridView or ListView and override the isInTouchMode method:

@override public Boolean isInTouchMode() {if(19 == Build.VERSION.SDK_INT){ return ! (hasFocus() && ! super.isInTouchMode()); }else{ return super.isInTouchMode();Copy the code

35, Remove the Listview scroll background black, item click default background

The default background of the ListView is transparent as the system window. If you add a background image or a background color to the ListView, the ListView will be black when scrolling, because the view inside the listView will be redrawn with the default transparent color (#FF191919).

  • Call listView setCacheColorHint(0) with the color set to 0
  • Android:cacheColorHint=”#00000000″ Android:cacheColorHint=”#00000000″ Android:cacheColorHint=”#00000000″ Android :listSelector=”#00000000″ after the above Settings, the ListView clicks on the item without any phenomenon

36. Open the Page for setting Android programs

Intent intent = new Intent();
intent.setClassName("com.android.settings","com.android.settings.ManageApplications");
intent.setAction("android.intent.action.MAIN");
try {
    startActivity(intent);
} catch (Exception e) {
    e.printStackTrace();
}Copy the code

37. Disallow EditText to automatically get the layout focus

Solution: Find one of the parent controls in EditText and set it to

android:focusable="true"  
android:focusableInTouchMode="true"Copy the code

This truncates the default behavior of EditText!

38. RadioButton Settings are selected by default

If a RadioButton is selected by default in the RadioGroup, two radiobuttons will be selected in the selection: There is no need to set RadioButton to be selected by default, so that RadioButton will always be selected. We should set the selected RadioButton to the RadioGroup, that is, radiobutton.setCheck (true); Changes to the radioGroup. Check (radioButton. GetId ());

39, Achieve ImageView width to fill the screen, height adaptive

1, custom ImageView override View onMeasure method

public class ResizableImageView extends ImageView { public ResizableImageView(Context context) { super(context); } public ResizableImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){ Drawable d = getDrawable(); if(d! =null){ // ceil not round - avoid thin vertical gaps along the left/right edges int width = MeasureSpec.getSize(widthMeasureSpec); Int height = (int) math.ceil ((float) width * (float) d.geetintrinsicHeight ()/(float) int height = (int) math.ceil ((float) width * (float) d.geetintrinsicheight () d.getIntrinsicWidth()); setMeasuredDimension(width, height); }else{ super.onMeasure(widthMeasureSpec, heightMeasureSpec); }}}Copy the code

2. Set the ImageView properties

Android :layout_width= "match_parent" Android :scaleType= "fitXY" Android :layout_height= "wrap_content" Make sure to set Android :adjustViewBounds= "true"Copy the code

Glide loads the web image to populate the ImageView in 39

Glide’s rules for loading images are based on the size of the ImageView. But the size of the ImageView fills the screen with the width of the ImageView. When the height is adjusted, the Glide loaded image will not display, so we choose a roundabout way to load: Request the image to be a bitmap, at which point the image has a certain size, and then set it to the ImageView to be adaptive:

Glide.with(GraphicDetailsFragment.this)
                    .load((new StringBuffer(Const.URL_HEAD).append(mStringList.get(position))).toString())
                    .asBitmap()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            viewHolder.mImageView.setImageBitmap(resource);
                        }
                    });Copy the code

How to remove the gaps around the Android GridView component

Set android:listSelector=”@null” to the GridView and the gap will be eliminated

42. Color of theme file Settings










ListView Sets the line spacing of the item and removes the dividing line

1. Set the line spacing of the item: You can set the XML attribute in the listView of the XML layout file: Android: Divider =”#00000000″ Android :dividerHeight=”18dp”

Explanation: The dividing line is transparent and the height is 18dp.

2. Remove the dividing lines between items: There are dividing lines between each item. If you simply want to remove the dividing lines, there are many ways:

  • Divider =”@null”
  • Law 2: Android: Divider =”@00000000″ The following two zeros are transparent
  • Method 3: setDividerHeight (0); Height is set to 0 | | ListView. SetDivider (null).
  • Method 4: android: divider = “@ drawable/listview_horizon_line”

The listView divider prints at the bottom of the header, item, and root. To cancel the header divider you must first set its method

addHeaderView(headView, null, true);
addFooterView(footView, null, true);Copy the code

Note: The third argument must be true or invalid

/ / show the head appear line listview. SetHeaderDividersEnabled (true); / / appears at the bottom of the forbidden line listview. SetFooterDividersEnabled (false);Copy the code

44, Error: Failed to create directory

Android stutio Error:Failed to create Directory “C: \ Users \ \ Administrator \. Gradle \ caches \ 2.8 \ scripts \ ijinit7_5jx13p26aqkoramvuhfn0lqca \ init \ classes’ this problem, The solution is to pop up a box with Invalidate Caches/Restart under the File. Click on the Invalidate and Restart button and wait for the Restart.

45. TextView appends a string

TextView.append(CharSequence text); // Append a string to the string cache based on an existing string; (Own opinion: it may cause repeated appends when refreshing the page, so it is not recommended)Copy the code

GetChildFragmentManger ();

Query: Two pieces are nested, and sending values to the second fragment via setArguments(bundle) can’t pass.

47. Hide the ListView scroll bar

SetScrollbarFadingEnabled (true); / / not hidden, activities when display setVerticalScrollBarEnabled (true); // Hide when you are inactive, and hide when you are activeCopy the code

Android: scrollbars = “none” and setVerticalScrollBarEnabled (true); Same effect.

Solve the problems caused by sliding conflicts

The divider and height cannot be set in the ListView. If the divider is set, the last item is not displayed completely. This is because onMeasure does not set the divider’s height into the ListView height when it sets the ListView height based on the entry.

Error importing third-party library

Error:Cannot change dependencies of configuration ':app:_debugAnnotationProcessor' after it has been resolved.

An error was reported while importing a third-party library. This is because the library relies on some library version that is too late and your Android Studio didn’t download it.

The height of the ScrollView

There is no match_parent in a ScrollView, so there is no reference to the height of the controls inside it. The invalidation of match_parent will manifest as wrap_content.

Java mind Mapping





Java mind mapping

Rxjava mind Map





Rxjava mind map

MVP structure diagram





MVP simple structure diagram

OnPrepareOptionsMenu and onCreateOptionsMenu

To create a menu on Android, you need to override the Activity’s onCreateOptionsMenu(Menumenu) method. This method is only called once when the Activity is first created, so if you want to change the menu dynamically afterwards, So you can’t do anything else with onCreateOptionsMenu, so you have to do onPrepareOptionsMenu(Menumenu).

OnPrepareOptionsMenu differs from onCreateOptionsMenu in that it is called every time the Menu hard key is pressed, so you can change the menu dynamically here.

Note: In the onPrepareOptionsMenu(Menumenu) function, you first need to call:

super.onPrepareOptionsMenu(menu);
menu.clear();Copy the code

If you do not clear and directly add, then the menu items will be “appended”, so that as you keep pressing the menu key, the menu items will continue to increase.

In addition, the android system default menu style is to support a maximum of three lines, if there are four items in each line of two lines… If you want to customize the style, you can define the style using an XML file.

56, android: parentActivityName

An Activity in manifet declares the Android: parentActivityName; Click the back button in the upper left corner of the Activity to start the declared parent Activity, and always call the parent Activity’s OnDestroy method first. When clicking the back button in the upper left corner of the child Activity, the call logic is as follows:

MainActivity.onDestroy();
MainActivity.onCreate(null);
MainActivity.onStart();Copy the code

Android :launchMode=singleTop to set the MainActivity property.

Imagine the android, by the way: the role of parentActivityName, is aimed at the upper left corner to the Activity to add a back button, specific information is as follows:

Android 4.1 Improves performance and enhances user experience By setting the android: parentActivityName change back the contents of the stack, if no parentActivity in stack, stack, synthesis, Change the contents of the parentActivity through onPrepareNavigateUpTaskStack ().

57. Conditional compilation

Conditional compilation (a concept in C) is a good thing, but there is no such pre-definition in the Java architecture. However, conditional compilation can be implemented based on Java compile-time optimization of code. Java has this rule in compilation: “The compiler optimizes the code, and the Java compiler will not generate bytecode for statements whose conditions are always false.” In this way, we only need to define an isDebug Boolean variable in Const (static variable class) and use it for code that we want to conditionally compile

If (isDebug) {... Code statement... }Copy the code

Student: Include. This way you can implement conditional compilation by controlling isDebug’s values. When isDebug is false, if… Code statement… Will be ignored by the compiler, that is, will not generate the corresponding bytecode.

58. Dynamically set the image path of ImageView

// The implementation principle is Java reflection? int resId = (Integer) R.drawable.class.getField("icon").get(null); holder.img.setImageResource(resId);Copy the code

One thing to understand is that the name of each image is a field of R.rawable

59, Static save of color list

Create an array file under Values:

<? The XML version = "1.0" encoding = "utf-8"? > <resources> <! -- Rainbow color for white font --> <integer-array name="itemcolor"> <item>0xFF79429D</item> <item>0xFF5691F5</item> <item>0xFF76BA55</item>  <item>0xFFB3E0E0</item> <item>0xFF27C9C2</item> <item>0xFF92AD6B</item> <item>0xFFEC4F4F</item> <item>0xFFEE6593</item>  <item>0xFFFFAC5A</item> <item>0xFF6296AF</item> <item>0xFFBF8A28</item> <item>0xFF319388</item> </integer-array> </resources>Copy the code

Note that the value of the color must be 8 bits, that is, the first two transparent bits cannot be omitted. And then you can get

Resources resources = context.getResources(); mColorArray = resources.getIntArray(R.array.itemcolor); . setBackgroundColor(R.id.... , mColorArray[Position % mColorArry.length]);Copy the code

60. ScrollView display is incomplete

Sometimes the ScrollView nested LinearLayout will not display completely, so you should check whether the parent of the ScrollView is using the CoordinatorLayout. When you are using CoordinatorLayout externally, you should use NestedScrollView internally, otherwise you will have uncertain bugs. When you use ViewPager & TabLayout inside the CoordinatorLayout to display different fragments, if you use ScrollView inside the Fragment, you will also have incomplete display.

The magic * / operation priority

double sin20 = Math.sin(Math.PI * 20 / 180); //0.3420201433256687 double sin201 = math.sin (20/180 * math.pi); / / 0.0

So that’s why 20/180 is an int, so it’s 0. So it’s going to be 0.

62, Alertdialog dialog box, set click other positions do not disappear

AlertDialog Android4.0 above on the edge of the touch dialog box outside, dialog disappear Can set up such a property, of course, you must first AlertDialog. Builder. The create () method to call these two method after a: setCanceledOnTouchOutside(false); When this method is called, pressing outside the dialog box does not work. Method 2: setCancelable(false); When this method is called, pressing outside the dialog box does not work. Pressing the back button doesn’t work either

63, Things to note about Vector

When used in the project you use Vector graphics, please note you can refer to www.jianshu.com/p/e3614e7ab… It’s also worth noting

//mDrawableActive = ContextCompat.getDrawable(context, R.drawable.vec_checkbox_fill_circle_outline); //mDrawable = ContextCompat.getDrawable(context, R.drawable.vec_checkbox_blank_circle_outline); // Resolve vector "resource not found" error, Can consider to use the method to replace the try {mDrawableActive = AppCompatDrawableManager. The get (). GetDrawable (context, R.drawable.vec_checkbox_fill_circle_outline); mDrawable = AppCompatDrawableManager.get() .getDrawable(context, R.drawable.vec_checkbox_blank_circle_outline); } catch (Resources.NotFoundException notFoundException) { Logger.e(notFoundException.getMessage()); } catch (Exception e) { Logger.e(e.getMessage()); } finally { mDrawableActive = context.getResources().getDrawable(R.drawable.vec_checkbox_fill_circle); mDrawable = context.getResources().getDrawable(R.drawable.vec_checkbox_empty_circle); }Copy the code

Also note that hardware acceleration does not seem to be turned off when using Vector:

Android: hardwareAccelerated = "false" / / do not use this setting in the configuration fileCopy the code

64. The OOM memory overflows

When you are testing your app, if it works on some models and OOM appears on some models, you can add the following to the configuration file in addition to making various optimizations for the app:

<application
    ...
    android:largeHeap="true"
    ...
    />Copy the code

It might be better.

65. Blank left side of the Toolbar (inside margin)

Cause: In the V7 package, the parent of wiget.appCompat. Toolbar property contentInsetStart(default value) is what causes the custom ActionBar to not fill completely.

<style name="ClubToolbar" parent="Widget.AppCompat.Toolbar"> <item name="contentInsetStart">0dp</item><! </style>Copy the code

Then override the Toolbar properties in AppStyle (must be here, setting the Toolbar style alone won’t work) :

<item name="toolbarStyle">@style/ClubToolbar</item>Copy the code

The use of DrawerLayout is small

DrawerLayout. SetDrawerListener (new ActionBarDrawerToggle); / / have animation menu icon DrawerLayout setScrimColor (Color. TRANSPARENT) / / remove the sideslip of shadow mask effect

NavigationView is translucent in all versions of the NavigationView. If not, you can remove it by setting the following properties:

app:insetForeground="@android:color/transparent"Copy the code

Also if you want Nav to be used with no background and full transparency just set the background to #00000000; Remove the background of headerLayout.

TextView is a native Bug

SDK:15~25 Test version: Android 6.0; Android 4.3 (exists on both versions and must exist in the middle)

<! -- Here we only set click events for the parent LinearLayout, <LinearLayout Android :id="@+ ID/LinearLayout "Android :layout_width="match_parent" android:layout_height="35dp" android:orientation="horizontal"> <TextView android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="match_parent" android:text="Time"/> <TextView android:id="@+id/time_value" android:layout_width="match_parent" android:layout_height="match_parent" android:inputType="date"/> </LinearLayout>Copy the code

I came across it by accident. If you set an inputType attribute to a TextView, inputType should not work, but there is an amazing thing that happens:

  1. If you set click events to the parent layout (@ID/Time_value), click in the @ID /time_value area and nothing happens, click in other areas such as @ID /time. (Other controls do not set any listening events)
  2. If you long press @ID /time_value area, the cursor (cannot be edited) will appear and the paste button prompt will appear. Click the paste button to paste and display the pasted text. (No listening events are set except for the parent layout)

ListView, RecyclerView, ScorllView, Viewpager and so on, cancel the top semicircle tension pattern

android:overScrollMode="never"Copy the code

69. EditText displays the height of two lines

Android: inputType = "textMultiLine" / / can display the multi-line android: gravity = "left | top" / / android: left upper corner of the input cursor minLines = "6" / / minimum shows six linesCopy the code

9 Pictures

The black edges on the left and top show the stretch area. The black edges on the right and below represent the fill area

NavigationView gets the controls in the HeaderLayout

NavigationView is a RecyclerView (or ListView before 23.1.0), and the header layout is usually element 0. In Support Library v23.1.1, you can easily get a view from the header using the following methods:

View headerLayout = navigationView.getHeaderView(0); // 0-index headerCopy the code

In version 23.1.0, this is the way to do it:

View headerLayout =
navigationView.inflateHeaderView(R.layout.navigation_header);
panel = headerLayout.findViewById(R.id.viewId);
// panel won't be nullCopy the code

72, Edittext input limits

Restrict input to certain values including numbers, letters, and so on

android:digits="0123456789abcdefghigklmnopqrstuvwxyz"Copy the code

The above line of code can be any restrictions you can only enter what can be written into the inside, the above says that only numbers and letters can be entered.

android:inputType="textPassword"  
android:digits="0123456789abcdefghigklmnopqrstuvwxyz"Copy the code

Android :inputType=”textPassword” android:inputType=”textPassword” Android :inputType=”textPassword” But if you add the android: who = “0123456789 abcdefghigklmnopqrstuvwxyz”, inputType Chinese here will fail, but the password can’t fail, here only for example, we all know.

InputType Attribute value

Android :inputType=" None "Android :inputType="text" Android :inputType="textCapCharacters" Uppercase letters Android :inputType="textCapWords" uppercase Android :inputType="textCapSentences" uppercase Android :inputType="textAutoCorrect" Auto-complete Android :inputType="textAutoComplete" Auto-complete Android :inputType="textMultiLine" multi-line input Android :inputType="textImeMultiLine" input method multiple lines (if supported) android:inputType="textNoSuggestions" android:inputType="textUri" Url Android :inputType="textEmailAddress" Email address Android :inputType="textEmailSubject" Email subject Android :inputType="textShortMessage" Short message Android :inputType="textLongMessage" long message Android :inputType="textPersonName" Name of a person Android :inputType="textPostalAddress" Address Android :inputType="textPassword" Password Android :inputType="textVisiblePassword" Visible password android:inputType="textWebEditText" as the text of the web form android:inputType="textFilter" textFilter Android :inputType=" TextTextTextType "Phonetic input // numeric type Android :inputType="number" numeric Android :inputType="numberSigned" symbol number format Android :inputType="numberDecimal" Floating point format Android :inputType="phone" dial keyboard Android :inputType=" dateTime "Time date Android :inputType="date" Date keyboard Android :inputType="time" time keyboardCopy the code

73, Jump activity, clear the previous activity stack

Problem description: During development, when logging out, the interface needs to jump to the login interface and clear all activities in the stack.

The solution

Intent intent = new Intent(A.this,B.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);  
startActivity(intent);Copy the code

FLAG_ACTIVITY_CLEAR_TASK is passed when startActivity is started. This flag will clear all previously opened activities. It will then become the root of another empty stack, and all other Activitys will be shut down. This method must be used with {@link #FLAG_ACTIVITY_NEW_TASK}.

74, LayoutInflater. The from (…). .inflate(…) Parameter explanation of

inflate(int resource, ViewGroup root, boolean attachToRoot)Copy the code
  1. If root is null, attachToRoot is useless and there is no point in setting any value.
  2. If root is not null and attachToRoot is set to true, a parent layout, root, is assigned to the loaded layout file.
  3. If root is not null and attachToRoot is set to false, all layout properties on the outermost layer of the layout file are set. These properties take effect automatically when the view is added to the parent view.
  4. When no attachToRoot parameter is set, if root is not null, the attachToRoot parameter defaults to true.

Large and small pits, everywhere, impossible to guard against. I will continue to update this blog post.

Click here for more Android tech articles

This blog is the author (OCN.Yang) original reprint please mark the original address: ocnyang.com/2016/08/31/…