RelativeLayout layout

  • Components are left aligned and top aligned by default

  • Android :layout_toRightOf=”@id/tv1″

  • Android :layout_below=”@id/tv1″

  • Set right aligned parent element Android :layout_alignParentRight=”true”

  • Set right alignment with specified component android:layout_alignRight=”@id/tv1″

LinearLayout

  • Specify the direction of each node

  • Set right aligned Android :layout_gravity=”right”

  • In a vertical layout, left-right alignment and horizontal center only, top and bottom alignment does not work

  • For horizontal layouts, align top and bottom and center vertically only

  • Be careful not to push other components out when using match_parent

  • Android :layout_weight=”1″

  • Weight: Allocates the remaining width or height of the screen proportionally

The frame layout FrameLayout

  • The default components are left and top aligned, and each component is equivalent to a div

  • You can set it up, down, left, right, horizontal, vertical, and center it in the same way as the linear layout.

  • Cannot be laid out relative to other components

TableLayout TableLayout

  • Each
    node is a row, and each of its children is a column

  • Nodes in a table layout may not have width and height set, because setting width and height does not work

    • The root node<TableLayout/>The width of the child node is the matching parent element, and the height is the content of the package
    • <TableRow/>The width and height of the child node of the node are the contents of the package
    • The above default properties cannot be modified
  • Android :stretchColumns=”1″ android:stretchColumns=”1″

AbsoluteLayout layout

  • Specify the x and y coordinates of the component directly

    android:layout_x="144dp"

    android:layout_y="154dp"

Note: direct copy project needs to change: project name, application package name, R file repackage

  • GetFilesDir () returns the path to the file object as data/data/application package name/files

    • Files stored in this path will remain there as long as you don’t delete them
  • GetCacheDir () returns the path to the file object as data/data application package name/cache

    • Files stored in this path may be deleted when memory runs out
  • System management application interface clear cache, will clear the cache folder under the things, clear data, will clear the whole package name directory under the things


  • Before 2.2, sdcard path: sdcard

  • Before 4.3, sdcard path: MNT /sdcard

  • 4.3 Start, SD card path: Storage /sdcard

  • File File = new File(“sdcard/test.txt”);

  • Use the API to obtain the real path of sd card, part of the mobile phone brand will change the path of the sd card Environment. External.getexternalstoragedirectory ()

  • To determine whether a sd card ready if (Environment. GetExternalStorageState (.) the equals (Environment. MEDIA_MOUNTED))


import java.io.File; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.text.format.Formatter; import android.widget.TextView; public class MainActivity extends Activity { private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); if(existSDCard()){ String available = formatSize(getAvailable()); String allSize = this.formatSize(getAllSize()); Tv.settext (" total space :"+allSize+" available "+available); }} / / access to available capacity private long getAvailable () {File path = Environment. External.getexternalstoragedirectory (); StatFs sf = new StatFs(path.getPath()); // Get the size of a single block (Byte) long blockSize = sf.getBlocksizelong (); / / get all the data blocks long availbleBlocks = sf. GetAvailableBlocksLong (); return blockSize* availbleBlocks; } / / get the total capacity private long getAllSize () {File path = Environment. External.getexternalstoragedirectory (); StatFs sf = new StatFs(path.getPath()); // Get the size of a single block (Byte) long blockSize = sf.getBlocksizelong (); Long allBlocks = sf.getBlockCountLong(); return blockSize*allBlocks; } private String formatSize(long size) {return formatter.formatfilesize (this, size); } / / whether the mount SD card private Boolean existSDCard () {if (Environment. GetExternalStorageState (.) equals ( Environment.MEDIA_MOUNTED)) { return true; } else return false; }}Copy the code

Note: in usegetBlockCountLong()Etc API when the main SDK version, SDK17 is not supportedgetBlockCountLong()The lower version of the SDK is still usedgetBlockCount()Without such asLongthe

Test categorization

  • Black box testing

    • Test logical service
  • White box testing

    • Test logic method
  • According to the test granularity

    • Method test: function test
    • Unit test: Unit test
    • Integration test: Integration test
    • System test: System test
  • Based on the level of violence tested

    • Smoke test: Smoke test(e.g. Monkey 1000: Tap 1000 times randomly on the screen)
    • A: Pressure test

Unit testing in Android

To start, use a class that inherits from AndroidTestCast:

import android.test.AndroidTestCase; Public class Test extends AndroidTestCase {public void Test (){public void Test (){public void Test (){Copy the code

And make the following configuration in:

<instrumentation android: Android :targetPackage=" application package name to test "> </instrumentation> <application Android :allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <! Android.test. runner --> <uses-library Android :/> </application>Copy the code
  • Lightweight relational databases

  • API to create database: SQLiteOpenHelper

    • The: onCreate method is called when the database is created
    • The: onUpgrade method is called when the database is upgraded
    import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class MyOpenHelper extends SQLiteOpenHelper { public MyOpenHelper(Context context) { // Parameter description: context, database name, cursor factory (default NULL), version (used for upgrade) super(context, "test.db", NULL, 1); } @override public void onCreate(SQLiteDatabase db) {execSQL("create table person(_id INTEGER primary key) autoincrement, name char(10), phone char(20), salary integer(10))"); } @override public void onUpgrade(SQLiteDatabase db, int oldVersion, Int newVersion) {system.out.println (" update database..." ); }}Copy the code

Creating a database

MyOpenHelper oh = new MyOpenHelper(getContext(), "test.db", null, 1); SQLiteDatabase db = oh.getwritableDatabase (); SQLiteDatabase = oh.getwritableDatabase ();Copy the code
  • GetWritableDatabase () : Opens a read-write database
  • GetReadableDatabase () : Opens a read-only database when disk space is insufficient; otherwise, opens a read-write database

Add, delete, change and check the database

Add, delete, change and check the database can use SQL statements, and then DB. ExecSQL (“SQL statement “) can be completed!

Note: Setup does initialization before testing, while teardown does garbage collection after testing.

@Override protected void setUp() throws Exception { super.setUp(); Oh = new MyOpenHelper(getContext(), "test.db", null, 1); } @Override protected void tearDown() throws Exception { super.tearDown(); Db.close (); }Copy the code

Add, delete, change and check using API

Public void select(){Cursor Cursor = db.rawQuery("select * from table name ", null); While (cursor.movetonext ()){// Get the column index from the column name, String STR = cursor.getString(cursor.getColumnIndex(" 1")); String STR = cursor.getColumnIndex(" 1"); String str2 = cursor.getString(cursor.getColumnIndex(" 1 ")); Int str3 = cursor.getint (cursor.getColumnIndex(" 表 名 ")); System.out.println(str+str2+str3); } } public void insertApi(){ ContentValues values = new ContentValues(); Values. Put (" field 1", "value"); Values. Put (" field 2", "value"); Values. Put (" field 3", "value"); Long l = db. Insert ("表名", null, values); } public void deleteApi(){int I = db.delete(" table name ", "_id =?", new String[]{"4"}); } public void updateApi(){ ContentValues values = new ContentValues(); Values. Put (" value", "value"); Int I = db.update("表名", values, "_id =?") , new String[]{"1"}); }Copy the code

The transaction

Ensure that multiple SQL statements either succeed or fail at the same time, in which case a rollback will occur!

Public void transaction(){try{// start transaction db.beginTransaction(); //TODO alter table data... / / set the transaction execution success, submitted if this line of code did not perform, will roll back the setTransactionSuccessful (); } catch (Exception e) {// The Exception must be caught e.printStackTrace(); } finally{// Close transaction, commit data db.endTransaction(); }}Copy the code

The getView method is called as many times as there are items on the screen, and as the screen slides down, getView continues to be called, creating more View objects to display on the screen

Caching of entries

When an item is scratched from the screen, the system caches it into memory. When the item is returned to the screen, the system passes in the cached item as the convertView parameter when it calls getView again, but it doesn’t have to be the same item that was previously cached. It is possible to pass in a cache of any item when you call the getView method to get the first item!

ArrayAdapter

Displays a string in the entry

String[] objects = new String[]{"AAA","BBB","CCC"}; ListView lv = (ListView) findViewById(R.id.lv); //arg1: specifies the layout file to populate. Lv.setadapter (new ArrayAdapter<String>(this, R.layout.item_array, R.I.D.v_name, objects));Copy the code

SimpleAdapter

You can display a variety of data in an entry

The data to be displayed is encapsulated in the List. Each element of the collection holds the data to be displayed in an entry. Since there may be multiple types of data, and the generic type of the collection can only specify one type of data, store the data in the Map first, and then put the Map in the List

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView)findViewById(R.id.lv); List< map <String, list <String, list < map <String, Object>> data = new ArrayList<Map<String,Object>>(); Map<String, Object> m1 = new HashMap<String, Object>(); m1.put("name","AAA"); m1.put("Photo",R.drawable.a); data.add(m1); Map<String, Object> m2 = new HashMap<String, Object>(); m2.put("name","BBB"); m2.put("Photo",R.drawable.b); data.add(m2); Map<String, Object> m3 = new HashMap<String, Object>(); m3.put("name","CCC"); m3.put("Photo",R.drawable.c); data.add(m3); lv.setAdapter(new SimpleAdapter(MainActivity.this, data, R.layout.item_listview, new String[]{"name","Photo"} , new int[]{R.id.name, R.id.iv}));Copy the code

SRC: project code 3. R.java: resource ID of all resource files in the project 4. Android.jar: Libs: import third-party JAR packages. 6. Assets: Store resource files, such as MP3 and video files. 7. Drawable: drawable: drawable: drawable: drawable: drawable: drawable: drawable: drawable: drawable Menu: defines the style of the menu. 12. Strings. XML: stores string resources, one for each resource

Android’s new virtual machine ART: Dalvik: Every time an application runs, bytecode needs to be converted into machine code by timely compilation, which slows down the startup of the application ART: Dalvik: When an application is first installed, the bytecode is precompiled into machine code, making it a true native application that can be launched and executed much faster

Adb install D:\weibo. Apk install APk adb uninstall package name uninstall APk ADB kill-server Kill ADB start-server start ADB Devices Adb shell Enters the Android command line to execute Linux commands

A Windows command: netstat -ano to check whether the port number is occupied (adb process is on port 5037, if the port is occupied will cause ADB startup failure)

Public void call(View v) {// Create an Intent Intent = new Intent(); Intent.setaction (intent.action_call); intent.setData(Uri.parse("tel:" + phone)); StartActivity (intent); }Copy the code
public void send(View v) { String mmsg = "Text"; String phone = "15291418231"; SmsManager sm = smsManager.getdefault (); ArrayList<String> message = sm.dividemessage (MMSG); // After truncation, send for (String mmsg_str: Message) {// Target number, // SMS center number (null uses the default value) // SMS text // Successfully sending or failing broadcast // Successfully receiving broadcast sm.sendTextMessage(phone, null, mMSg_str, null, null); }}Copy the code
  • Define a MyListener to implement the onClickListener interface
  • Define an anonymous inner class that implements the onClickListener interface
  • Make the current activity implement the onClickListener interface
  • Set the onClick property to the Button node and define a method in the activity with the same name as the value of that property

Px and DP: DP is related to density, px is pixel, it is easier to use DP for screen adaptation