Android Common layout

Source: Internet
Author: User
Tags config log relative backup

Project Source Download

Https://github.com/Wang-Jun-Chao/AndroidProjects

Common layouts

Relative layout

Relativelayout

Components are left-aligned and top-aligned by default

Sets the component to the right of the specified component

 android:layout_toRightOf="@id/tv1"

Set at the bottom of the specified component

android:layout_below="@id/tv1"

Set right-aligned parent elements

android:layout_alignParentRight="true"

Sets the right alignment to the specified component

 android:layout_alignRight="@id/tv1"

Linear layout

LinearLayout

Specify the direction in which each node is arranged

android:orientation="horizontal"

Set Right alignment

android:layout_gravity="right"

When vertical layout, only the left and right alignment and horizontal center, the top bottom alignment vertical Center is invalid

When horizontal layout, only the top of the bottom is aligned and vertically centered

When using match_parent, be careful not to top out other components

A very important attribute of linear layout: weight

android:layout_weight="1"

Weights are set to distribute the remaining space proportionally

Frame layout

Framelayout

The default components are left-aligned and top-aligned, with each component equivalent to a div

You can change the alignment

android:layout_gravity="bottom"

cannot be laid out relative to other components

Table layout

Tablelayout

Each node is a row, and each of its child nodes is a column

The nodes in the table layout can not be set to a wide height because the settings are also invalid

The child nodes of the root node are wide to match the parent element, high as the wrapped content

The node's child nodes are broadly wrapped, and the contents are high.

The above default properties cannot be modified

The following properties can be set in the root node to allow the 1th column to stretch to fill the remaining space of the screen width

android:stretchColumns="1"

Absolute layout

Absolutelayout

Specify the x, y coordinates of the component directly

android:layout_x="144dp"
android:layout_y="154dp"

Logcat

Total log information is divided into 5 levels

Verbose

Debug

Info

Warn

Error

Define filters for easy viewing

The log level of the System.out.print output is Info,tag is System.out

The log output API provided by Android

Log.v(TAG, "加油吧,童鞋们");
Log.d(TAG, "加油吧,童鞋们");
Log.i(TAG, "加油吧,童鞋们");
Log.w(TAG, "加油吧,童鞋们");
Log.e(TAG, "加油吧,童鞋们");

File read and write operations

RAM memory: Running memory, equivalent to computer memory

ROM Memory: Internal storage space, the equivalent of a computer's hard disk

SD card: External storage space, the equivalent of a computer's mobile hard disk

Read and write files in the internal storage space

Small case: User input account password, tick "Remember account password", click on the login button, login and persistent save account and password

1. Define Layout

2. Click event to complete the button

Pinball Prompts User Login success

Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();

3. Get the user input data

To determine whether users check the password to save the account

CheckBox cb = (CheckBox) findViewById(R.id.cb);
if(cb.isChecked()){

}

4. Open IO Stream to write files to internal storage

Directly open file output stream write data

//持久化保存数据
    File file = new File("data/data/com.itheima.rwinrom/info.txt");
    FileOutputStream fos = new FileOutputStream(file);
    fos.write((name + "##" + pass).getBytes());
    fos.close();

Detects whether a file exists before reading data

if(file.exists())

Read the saved data, also directly open the file input stream read

File file = new File("data/data/com.itheima.rwinrom/info.txt");
FileInputStream fis = new FileInputStream(file);
//把字节流转换成字符流
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String text = br.readLine();
String[] s = text.split("##");

After reading to the data, echo back to the input box

et_name.setText(s[0]);
et_pass.setText(s[1]);

Applications can only create files under their own package names, not to other people's home to create

Copy items directly

Where to change:

Project name

Apply Package Name

R file re-guide package

Using the path API to read and write files

Getfilesdir () The path to the file object is Data/data/com.itheima.rwinrom2/files

The file stored in this path, as long as you do not delete it, has been

Getcachedir () The path to the file object is Data/data/com.itheima.rwinrom2/cache

Files stored in this path may be deleted when there is not enough memory

System Management application interface to clear the cache, will clear the cache folder of things, clear data, will clear the whole package of items recorded

Storing read and write data externally

Path to SD card

sdcard:2.3 before the SD card path

mnt/sdcard:4.3 before the SD card path

SD card path after storage/sdcard:4.3

The simplest way to open an SD card

File file = new File("sdcard/info.txt");

Need permission to write SD card

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Read the SD card, do not need permission before 4.0, after 4.0 can be set to require

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Using the API to obtain the true path of SD card, some mobile phone brands will change the SD card path

Environment.getExternalStorageDirectory()

Determine if the SD card is ready

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))

View source code find code to get the remaining capacity of SD card

Import the Settings project

Find "free space" to get

 <string name="memory_available" msgid="418542433817289474">"可用空间"</string>

Find "memory_available" and get

<Preference android:key="memory_sd_avail" 
    style="?android:attr/preferenceInformationStyle" 
    android:title="@string/memory_available"
    android:summary="00"/>

Find "Memory_sd_avail" and get

//这个字符串就是sd卡剩余容量
formatSize(availableBlocks * blockSize) + readOnly
//这两个参数相乘,得到sd卡以字节为单位的剩余容量
availableBlocks * blockSize

The storage device is divided into blocks, each with a fixed size

Chunk size * Number of blocks equals total size of storage device

Access permissions for Linux files

In Android, each application is an independent user

Drwxrwxrwx

1th: D means folder,-represents file

第2-4位: rwx, which indicates the owner user (owner) of this file has permissions on the file

R: Read

W: Write

X: Performing

第5-7位: Rwx, which represents the permissions of a user (grouper) to the same group as the file owner user

第8-10位: Rwx, which represents the permissions of users (other) of other user groups on the file

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/

Four modes of Openfileoutput

mode_private:-rw-rw--

mode_append:-rw-rw--

mode_world_writeable:-rw-rw–w-

mode_world_readable:-rw-rw-r–

Sharedpreference

Store account password with Sharedpreference

Write data to Sharedpreference.

//拿到一个SharedPreference对象
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
//拿到编辑器
Editor ed = sp.edit();
//写数据
ed.putBoolean("name", name);
ed.commit();

Take the data from the sharedpreference.

SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
//从SharedPreference里取数据
String name = sp.getBoolean("name", "");

Generate XML file Backup SMS

Create a few virtual SMS objects that exist in the list

Backup data is usually backed up to SD card

Using StringBuffer to stitch strings

Append all the nodes in the XML file into SB object

sb.append("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>");
//添加smss的开始节点
sb.append("<smss>");
.......

Write SB into the output stream

fos.write(sb.toString().getBytes());

To generate an XML file using an XML serializer

Get XML Serializer Object

XmlSerializer xs = Xml.newSerializer();

To set the output stream for the serializer

File file = new File(Environment.getExternalStorageDirectory(), "backupsms.xml");
FileOutputStream fos = new FileOutputStream(file);
//给序列化器指定好输出流
xs.setOutput(fos, "utf-8");

Start generating XML files

xs.startDocument("utf-8", true);
xs.startTag(null, "smss");
......

Pull parsing XML files

Write your own XML file, save some weather information

Get the XML file

    InputStream is = getClassLoader().getResourceAsStream("weather.xml");

Get the pull parser.

    XmlPullParser xp = Xml.newPullParser();

Start parsing

Get the event type of the current node where the pointer is located

int type = xp.getEventType();

There are five main types of events

Event types for Start_document:xml headers

Event type at end of End_document:xml

Start_tag: Event type for start node

End_tag: Event type for end node

Text: The event type of the literal node

If the event type is not end_document, the parsing is not completed, and if it is, parsing completes, while the loop ends

while(type != XmlPullParser.END_DOCUMENT)

When we parse to different nodes, we need to do different things, so we'll judge the name of the current node.

When parsing to the start node of the weather, the new out list

When parsing to the start node of city, create the city object to make it easier to save the text that is about to be resolved

When parsing to the name start node, gets the text content of the next node, as does temp and PM.

case XmlPullParser.START_TAG:
//获取当前节点的名字
    if("weather".equals(xp.getName())){
        citys = new ArrayList<City>();
    }
    else if("city".equals(xp.getName())){
        city = new City();
    }
    else if("name".equals(xp.getName())){
        //获取当前节点的下一个节点的文本
        String name = xp.nextText();
        city.setName(name);
    }
    else if("temp".equals(xp.getName())){
        String temp = xp.nextText();
        city.setTemp(temp);
    }
    else if("pm".equals(xp.getName())){
        String pm = xp.nextText();
        city.setPm(pm);
    }
    break;

When parsing to the end node of city, the three subnodes of city are all resolved, and the city object is added to the list

case XmlPullParser.END_TAG:
    if("city".equals(xp.getName())){
            citys.add(city);
    }
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.