Android View And Activity

View与GroupView

The graphical interface in Android is composed of View and ViewGroup and their subclasses: View: The parent class of all visual controls, providing component depiction and time processing methods. ViewGroup: A subclass of the View class, which can have child controls, which can be regarded as the controls in the container Android UI are stacked according to this hierarchical tree structure. There are two ways to create a UI layout. Write your own code in Java or define the layout through XML. The latter is more convenient and easy to understand! It is also our most commonly used method! In addition, we generally rarely use View and ViewGroup to write layouts directly, and more often use their subclass controls or containers to build layouts!
The following is the content of this article, the following cases are for reference

What is the layout?

Layout is the rule for placing controls, and you can think of layout as a transparent container.
The controls are placed inside the transparent container according to the rules.
Just pay attention to the beginning of android:.
There are six major layouts in Android, namely:

  1. LinearLayout (linear layout)
  2. RelativeLayout (relative layout)
  3. TableLayout (table layout)
  4. FrameLayout (frame layout)
  5. AbsoluteLayout (absolute layout)
  6. GridLayout (grid layout)

Today we are going to explain the first two layouts.
LinearLayout (linear layout), the more we use for screen adaptation is the weight (weight attribute) of LinearLayout.

Linear layout

Linear layout means that the internal controls are arranged in a row horizontally or vertically.
android:orientation="vertical" direction
Optional values: horizontal (horizontal), vertical (vertical)

Linear layout supports proportional division.

//共同作用分宽度
android:layout_width="0dp"
android:layout_weight="2"

Relative layout

In a certain direction or position of a reference object, the first step of the relative layout is to give the reference object a name (id). In the
relative layout, if you do not specify the relative position of the child controls, they are stacked in the upper left corner by default.
Example: Create a new layout file

  1. Select res—layout folder, right click—New—Android XML File
  2. In the File column of the pop-up window, enter the name of the layout file to be created (all English lowercase, use _ to separate between words)
  3. Select the layout to be used in the Root Element column below and click the Finish button to complete the creation
给某个布局或控件起一个id
android:id="@+id/text1"

在某个参照物的右边
android:layout_toRightOf="@id/text1"
在某个参照物的左边
ndroid:layout_toLeftOf="@id/text1"
在某个参照物的下面
android:layout_below="@id/text1"
在某个参照物的上面
android:layout_above="@id/text1"

在父控件的中间
android:layout_centerInParent="true"
在父控件的水平中心
android:layout_centerHorizontal="true"
在父控件的垂直中心
android:layout_centerVertical="true"

对齐父控件的左边
android:layout_alignParentLeft="true"
对齐父控件的右边
android:layout_alignParentRight="true"
对齐父控件的顶端
android:layout_alignParentTop="true"
对齐父控件的底部
android:layout_alignParentBottom="true"

对齐某个控件的左边/右边
android:layout_alignLeft="@id/btn1"
android:layout_alignRight="@id/btn1"
对齐某个控件的顶端/底部
android:layout_alignTop="@id/btn1"
android:layout_alignBottom="@id/btn1"

Layout nesting

Layouts can be nested. For the outer layout, the inner layout is also equivalent to a control.
In theory, the layout can be nested at any level, but for performance reasons, nesting should be used as little as possible.

Common controls

TextView text display control

设置显示文字
android:text="我今晚想吃卷饼" 

如果给TextView设置比较大的宽度和高度时,文字默认在左上。
可以通过设置重力方向来控制文字的位置。
android:gravity="center"

设置文字大小(单位使用sp)
android:textSize="10sp"

设置为浏览器的超链接
android:autoLink="web"

Button button and ImageButton

Button是TextView的子类,拥有TextView的绝大多数属性。
In addition, as a subclass, Button has also made some changes to its parent class TextView.
For example: the text is centered by default, which increases the click effect of the button.

ImageView picture display control

Function for displaying pictures

设置显示的图片
android:src="@drawable/xxx"

Picture naming rules:

  1. Do not allow the beginning of a number
  2. Uppercase English is not allowed
  3. Chinese and special symbols are not allowed
    drawable目录中有任何一个违规的都不行

GridView Grid view

    <GridView
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:horizontalSpacing="10dp"
        android:numColumns="3"
        android:verticalSpacing="30dp" >
    </GridView>

The effect is as follows:

Listener

It is similar to setting up a certain "agreement" in advance (a certain condition A → execute a certain piece of code B·).
If this condition A is reached during the running of the program, then B is automatically triggered.
If condition A is not fulfilled while the program is running, B will never be triggered.

"Everything is an object"
Layout controls in xml (control must have id) → find the object in .java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        //按钮绑定id
        mBtn = (Button) findViewById(R.id.btn1);
        mBtn.setOnClickListener(new OnClickListener() {
    
    
            
            @Override
            public void onClick(View v) {
    
    
                //创建一个Intent对象
                //1.导包
                //2.参数一:当前的类名.this   参数二:要跳转的类名.class
                Intent intent = new Intent(MyActivity.this,MainActivity.class);
                //跳转
                startActivity(intent);
            }
        });
    }

The AndroidMainfest.xml manifest configuration file
Manifest configuration fileneeds to configure the activities of other pages into the manifest file.

Multiple buttons, multiple listeners:

//1.使用当前的MainActivity主页面类实现OnClickListener接口
public class MainActivity extends Activity implements OnClickListener {
    
    

    private Button mBtn1, mBtn2, mBtn3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBtn1 = (Button) findViewById(R.id.btn1);
        mBtn2 = (Button) findViewById(R.id.btn2);
        mBtn3 = (Button) findViewById(R.id.btn3);
        
        //设置点击事件监听器
        //A:点击事件  OnClick
        mBtn1.setOnClickListener(this);
        mBtn2.setOnClickListener(this);
        mBtn3.setOnClickListener(this);
    }

    /**
     * 
     * @param v 点击的按钮的对象
     */
    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()) {
    
     //获得点击的控件的id
        case R.id.btn1: //B1
            Toast.makeText(MainActivity.this, "您点击了按钮1", Toast.LENGTH_SHORT).show();
            break;
        case R.id.btn2: //B2
            Toast.makeText(MainActivity.this, "您点击了按钮2", Toast.LENGTH_SHORT).show();
            break;
        case R.id.btn3: //B3
            Toast.makeText(MainActivity.this, "您点击了按钮3", Toast.LENGTH_SHORT).show();
            break;
        }
    }
}

Output Log

Output some debugging information at the key nodes of the program. This information cannot be perceived by the user, but can be intercepted by the developer in the background.

//tag:日志的标签
//msg:日志显示的内容
Log.d(String tag,String msg)

Example: Click a button to output a sentence of debugging information in the background.

Two ways to capture logs
: 1. IDE (Integrated Development Environment): Eclipse

  1. Confirm whether the current environment is connected to the corresponding simulator, click Open Perspective... (upper right corner)
  2. Select the DDMS window in the new window and click the Open button
  3. In the Devices tab of the DDMS window, confirm that the device is connected
  4. After confirming that the connection is correct, return to the logcat window of the edit window
  5. In the upper left corner of the Logcat window, click the green plus sign
  6. In the new pop-up window, enter the label name (such as MainActivity) in the first two blanks, and click the OK button.

2. adb (Android debugging bridge) ------ It is recommended
to configure environment variables first.
Enter the directory of the development environment, there is an sdk folder, and there is a platform-tools folder inside.
Copy the path of platform-tools to the environment variable.

  1. Click Win+R, enter cmd, and press Enter.
    In the black window of the command line, enter adb and press Enter to verify.
  2. adb command:
    verify the connected device
    adb devices
  3. Filter Log
    adb logcat -s tag name, for example:
    adb logcat -s MainActivity

Toast basic use

Call the makeText() method of the Toast class directly

 @Override
            public void onClick(View v) {
    
    
                //B:弹出个小窗提示
                //参数一:固定搭配
                //参数二:要显示的文字
                //参数三:持续时长Toast.LENGTH_SHORT或者Toast.LENGTH_LONG
                Toast.makeText(MainActivity.this, "点击了", Toast.LENGTH_SHORT).show();
            }

Basic use of Intent

The hub between the four major components-Intent (intent), Android communication bridge.

MainActivity.java: Send data

public class MainActivity extends Activity {
    
    
    
    private TextView mText1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mText1 = (TextView) findViewById(R.id.text1);
        
        //设置显示的内容
        mText1.setText("https://mini.eastday.com//a//201218135517111.html?qid=juheshuju&referrer=");
        //设置点击事件的监听器
        mText1.setOnClickListener(new OnClickListener() {
    
    
            
            @Override
            public void onClick(View v) {
    
    
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                //携带参数(参数一:数据名称;参数二:数据的值)
                intent.putExtra("data", mText1.getText());
                startActivity(intent);
            }
        });      
    }
}

Second.java receives and displays data

public class SecondActivity extends Activity{
    
       
    private TextView mText;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        mText = (TextView) findViewById(R.id.text_custom);
        
        //获取上个页面跳转来的数据
        String text = getIntent().getStringExtra("data"); //参数是数据的名称,见发送的时候的第一个参数
        //设置到TextView上
        mText.setText(text);
    }
}

Activity

Activity is a component of an application. It provides an area on the screen that allows users to do some interactive operations on it, such as making a call, taking a picture, sending an email, or displaying a map! Activity can be understood as a window that draws the user interface, and this window can fill the entire screen, or it may be smaller than the screen or float above other windows!

Life cycle

Insert picture description here回调方法: A method to be called automatically at a specific timing (system timing, no need to manually set).
Activity will call back a specific method at each specific timing, and the user can call some code at these specific timings.

-----The page starts to start-----
D/MainActivity( 2349): onCreate
D/MainActivity( 2349): onStart
D/MainActivity( 2349): onResume
------Foreground running status---- -----
------- Start to
return to the background-------- D/MainActivity( 2349): onPause
D/MainActivity( 2349): onStop
-------- Fully in Background --------
--------Start to return to the foreground --------
D/MainActivity( 2349): onStart
D/MainActivity( 2349): onResume
------ ---Foreground running state--------
---------Close the page (for example, click the back button)------
D/MainActivity( 2349): onPause
D/MainActivity( 2349 ): onStop
D/MainActivity( 2349): onDestroy


Start/destroy of onCreate/onDestroy page
An Activity instance will only be called once.

onStart/onStop
starts to enter the foreground/completely in the background

onResume/onPause is
completely in the foreground/begins to enter the background

Time-consuming operations cannot be performed in onPause and should be executed in onStop.

Activity loading mode

standard standard mode

Each startup will create a new instance into the stack.

singleTop stack top multiplexing mode

If the next page to be launched happens to be the page currently being displayed, no new instance will be created at this time.

SingleTask in-stack reuse mode

1. Include stack top reuse
. 2. If the next page to be started already exists in the stack before, then this instance will be reused, and
other instances above this instance will be popped from the stack.

singleInstance singleton mode

  1. There is only one instance globally
  2. A single stack
  3. When exiting the stack, the current active stack will be cleared first, and then switched to other stacks until all stacks of this App are cleared.

Application

Any App has a unique Application instance, which is used to manage all processes of the entire App.
Application features are suitable for data transfer during app operation.
By default, Application is designed by Google and does not provide data transfer and temporary storage functions.
The user needs to manually override the official Application class and replace it with a custom Application class to achieve this function.

Custom Application

  1. Register a custom Application in the manifest file (add the name attribute)
  2. Create a custom Application class file under the src package
  3. Let the custom class inherit the Application class. import android.app.Application;

MainActivity.java

public class MainActivity extends Activity {
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //演示如何在每一个Acitivity中获得MyApplication对象并存取数据
        MyApplication app = (MyApplication) getApplication();
        app.putData("data", "这是我扔进去的数据");
        
        //加入下面的代码是另外一个地方的Activity
        MyApplication app2 = (MyApplication) getApplication();
        String value = (String) app2.getValue("data");
        Toast.makeText(MainActivity.this, value, Toast.LENGTH_SHORT).show();
    }
}

MyApplication.java

public class MyApplication extends Application{
    
    
    private HashMap<String,Object> mData = new HashMap<String, Object>();
    
    //添加数据
    public void putData(String key,Object value) {
    
    
        mData.put(key, value);
    }

    //获取数据
    public Object getValue(String key) {
    
    
        return mData.get(key);
    }
}

Tip:
All on-origin methods in Android do not need to be manually called by the user.
These methods will be called at specific times.
In fact, these functions are callback functions.

Object类是所有类的父类,Object可以使用多态来保存任何类型。

Guess you like

Origin blog.csdn.net/qq_43600467/article/details/112093885