The basics of Android Studio application, teach you step by step from entry to proficiency (Xiaobai learning) Summary 1 Basic introduction + intent + common controls

Say on top:

These are the notes I compiled based on the teaching video of station B. The codes in the video are hand-typed, debugged and error-free.

 B station teaching video link: (Must be learned after learning) Android studio basics, from entry to proficiency, even beginners can learn after learning_哔哩哔哩_bilibili

Summary 2 is writing hard~ to be continued


Table of contents

1. Basic application

 build.gradle file

Modify the icon and name of the APP

Use of the Log method and the LogCat window

new activity

Create a layout file

Create a new button in the layout

display layout in activity

Register the activity in manifest.xml

add button

add menu

2. Intent realizes activity jump

1. Explicit intent

2. Implicit Intent

2.1. Implicit preliminary application

2.2. Access external link of implicit intent application

2.3. Calling the system dialing interface of the implicit intent application

3. Intent implements data transfer

Use intent's putExtra() method for data transfer

3. Controls

1. TextView control

2. button control

3. EditText control

3.1 Display of input box

3.2 Combined use with button

4. ImageView control

 4.1 Display of picture controls in layout files

4.2 Realize clicking the button to change the picture application

4.3 Click the button to convert the image application

layout file

active file

5. ProgressBar control

 5.1 Progress bar display in layout file

5.2 Click to make the progress bar appear/disappear

5.3 Modify the progress bar style and progress

Four, Dialog dialog box

1. AlertDialog prompt information

4.2 Prompt message of ProgressDialog


1. Basic application

 build.gradle file

All relevant configurations are specified in the build.gradle (:app) file, such as SDK version, APP version number and name, etc. (will be used when the subsequent APP is upgraded)

Modify the icon and name of the APP

Modify the name and icon of the APP in manifest.xml, the icon needs to be changed to icon and roundicon

Use of the Log method and the LogCat window

The log function can be debugged in mainactivity.java, and the required information can be searched in the logcat window

// 打印最琐碎的信息
        Log.v(TAG,"onCreate");
//  information,打印重要数据
        Log.i(TAG,"onCreate");
//  warning,打印警告信息
        Log.w(TAG,"onCreate");
//   error,打印错误信息
        Log.e(TAG,"onCreate");
// debug,打印调试信息
        Log.d(TAG,"onCreate");


new activity

Create a new activity in the same directory as MainActivity, select empty activity


Create a layout file

Create a new layout in the layout directory, new layout recourse


Create a new button in the layout

Add height and width attributes to modify the text content of the button

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <Button
        android:id="@+id/Button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按钮1"></Button>


</androidx.constraintlayout.widget.ConstraintLayout>


display layout in activity

setContentView method, use R.layout.xxx to refer to the defined layout

setContentView(R.layout.first_layout);


Register the activity in manifest.xml

That is, to add the main activity, etc., you need to add the following code,

android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>


You can also modify the name of the main activity, such as defining android:label="main interface"

 <activity
            android:name=".MainActivity"
            android:label="主界面"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


add button

1. Add buttons to the layout
In the first_layout file:

<Button
        android:id="@+id/Button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/button1_name"></Button>

2. Add a button in java, use the Toast method to pop up the window
In the main activity file: define a button

Button b1 = (Button)findViewById(R.id.Button1);
b1.setOnClickListener(new View.OnClickListener(){
    @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "你按痛我啦", Toast.LENGTH_SHORT).show();
            }
        });

add menu

1. Create a new folder named menu under the package file, create a new menu file named main under this folder, and use the item tag to set the id and content for the two submenus under the menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/add_item"
        android:title="我是一个添加"></item>

    <item android:id="@+id/remove_item"
        android:title="我是一个删除"></item>
</menu>

2. Rewrite two methods in MainActivity.java to display the menu and the corresponding pop-up window after clicking the button

    //    重写onCreateOptionsMenu,设置菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
//        显示创建的菜单是否显示
        return true;
    }

// 为菜单添加点击弹窗
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.add_item:
                Toast.makeText(this, "这是一个添加菜单", Toast.LENGTH_SHORT).show();
                break;
            case R.id.remove_item:
                Toast.makeText(this, "你确定要删除吗?", Toast.LENGTH_SHORT).show();
                break;
            default:
        }
        return true;
    }


2. Intent realizes activity jump

Intents are intents that can be used to convert activities.

1. Explicit intent

Clearly specify the activity you want to jump to, so it is called an explicit intent. The created intent object passes in 2 parameters:

  • The first parameter MainActivity.this represents the current activity
  • The second parameter SecondActivity.class represents the target activity to jump to

Add intent to the button click event to complete the jump between the main activity MainActivity and SecondActivity, and then use the startActivity method to convert the activity 

Button b1 = (Button)findViewById(R.id.Button1);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "你按痛我啦", Toast.LENGTH_SHORT).show();
//                使用显示intent跳转活动
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        });

2. Implicit Intent

2.1. Implicit preliminary application

Do not clearly indicate the activity you want to jump to, configure it through <intent-filter> in the configuration file

  • Enter the configuration area of ​​the second activity, add the <intent-filter> tag, specify the name and category you want to jump to this activity 
  • 分别为 <action android:name="jump_to_second_activity"></action>和
      <category android:name="android.intent.category.DEFAULT"></category>
<activity
            android:name=".SecondActivity"
            android:label="第二界面"
            android:exported="false">
            <intent-filter>
                <action android:name="jump_to_second_activity"></action>
                <category android:name="android.intent.category.DEFAULT"></category>
            </intent-filter>

        </activity>
  • Modify the corresponding click method at the button click event, and modify the required parameters of the construction method of the new Intent object, which becomes the name of the activity you want to jump to, that is, "jump_to_second_activity" defined in the previous step.
  • The system will automatically add the category "android.intent.category.DEFAULT" to the intent, so there is no need to specify the label to jump to.
 b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "你按痛我啦", Toast.LENGTH_SHORT).show();
//                使用显示intent跳转活动
//                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
//                使用隐式intent
                Intent intent = new Intent("jump_to_second_activity");

                startActivity(intent);
            }
        });

2.2. Access external link of implicit intent application

  • Add a new button in the first_layout layout file, which is responsible for jumping to the Baidu link, and then add a click event corresponding to the button b1_1 in the main activity, the effect is as follows.

  • Note, use Intent.ACTION_VIEW to create the intent object, and then call the setData method, and the incoming parameter is the corresponding URL. 
Button b1_1 = (Button) findViewById(R.id.Button1_1);
        b1_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this,"打开网页",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("http://www.baidu.com"));
                startActivity(intent);
            }
        });

2.3. Calling the system dialing interface of the implicit intent application

Change the parameters in parse to "tel:******" 

Button b1_2 = (Button) findViewById(R.id.Button1_2);
        b1_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this,"打开拨号界面",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("tel:10086"));
                startActivity(intent);
            }
        });

3. Intent implements data transfer

Use intent's putExtra() method for data transfer

  • putExtra() for data saving

In the click of the main activity to jump to the button of the second activity, transfer the string data

1. Define the string data

2. Use an explicit intent to transfer data, and then use the putExtra method to store the data in the intent. This method requires two parameters, one is the stored data name, the other is the stored data value, and the stored data name It is StringInformation, the data value is the content of data 

// 把java中的按钮和布局中的联系起来
        Button b1 = (Button)findViewById(R.id.Button1);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "跳转到第二个活动", Toast.LENGTH_SHORT).show();

//                在向第二个活动转换的过程中传递一个字符串
                String data = "你好,第二个活动!";

//                使用显示intent跳转活动
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
//                把需要传递的数据存入intent中,第一个参数是传递的数据名称,第二个参数是取得的实际值内容
                intent.putExtra("StringInformation",data);

//                使用隐式intent
//                Intent intent = new Intent("jump_to_second_activity");
                //intent.addCategory("my_category");
                startActivity(intent);
            }
        });
  • getXxxExtra() to fetch data

After activity 2 displays the layout statement, start to fetch data from the intent 

1. Use the getIntent method to define an intent object

2. Because the value to be obtained is string type, use the getStringExtra method. The parameter passed in the method is the name "StringInformation" of the data defined above

3. Use the logcat window to print information and check whether it is successful

//        新建一个获取数据的intent
        Intent intent = getIntent();
//        获取存再intent中的名为StringInformation的字符串
        String data =intent.getStringExtra("StringInformation");
//        在logcat窗口中打印对应信息
        Log.d("SecondActivity",data);

Test: print successfully

3. Controls

1. TextView control

Create a new empty activity, and set the properties of the TextView control in the main_activity layout file

  • android:gravity sets the position of the text, center is the centered display
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="17sp"
        android:textColor="@color/purple_200"
        android:text="我是一行文字,欢迎来到textview的学习">
    </TextView>

</LinearLayout>

Effect:

2. button control

We are already very familiar with the use of buttons, here is a new textAllCaps attribute, because Android studio will automatically convert the lowercase letters in the button to uppercase letters, so if you need to keep lowercase, set the attribute to false, so that lowercase letters can be kept . 

<Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello everyone! 我是一个按钮"
        android:textAllCaps="false">
    </Button>

In the activity, the button click can be added

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

        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.button1:
//                        逻辑控制
                        break;
                    default:
                        break;
                }
            }
        });
    }

3. EditText control

3.1 Display of input box

The hint attribute displays the text to be displayed in the input box 

<EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="快点给我的输入框里输入文字吧!">
    </EditText>

3.2 Combined use with button

Enter text in the input box, click the button, and the corresponding content in the input box will pop up in the interface (toast method) 

  • Create an EditText object
  • Use the findViewById method to link layout files and java objects
  •  Add the following code in the logic control statement of the button click
  • String inputText = editText.getText().toString(); The getText() method is used to obtain the text entered in the text box, and the toString() method is used to convert it into a string type.
  •  Toast.makeText(MainActivity.this, inputText, Toast.LENGTH_SHORT).show(); Pop up the corresponding content
public class MainActivity extends AppCompatActivity {

//    创建一个输入框对象
    private EditText editText;

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

        Button b = (Button) findViewById(R.id.button1);

//       和按钮一样,使用findviewbyid 获取到输入框的实例
        editText = (EditText)findViewById(R.id.edit_text);

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.button1:
//                        逻辑控制
                        String inputText = editText.getText().toString();
                        Toast.makeText(MainActivity.this, inputText, Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }
        });
    }
}

4. ImageView control

 4.1 Display of picture controls in layout files

  <ImageView
        android:id="@+id/image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/img2">
    </ImageView>

4.2 Realize clicking the button to change the picture application

Preparations: place two resource images in the drawable, and create a new button b2

  • Create a new imagView object: private ImageView imageView;
  •  获取imageview的id:
     imageView =(ImageView) findViewById(R.id.image_view);
  • Use the setImageResource() method to set the image to be replaced in the click event of the button, and use R.drawable.xxx to reference: imageView.setImageResource(R.drawable.img1);
package cn.edu.sdut.uipractice01;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

//    创建一个输入框对象
    private EditText editText;
//    创建一个imageview对象
    private ImageView imageView;

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

        Button b1 = (Button) findViewById(R.id.button1);
        Button b2 = (Button) findViewById(R.id.button2);

//       和按钮一样,使用findviewbyid 获取到输入框的实例
        editText = (EditText)findViewById(R.id.edit_text);
//        获取imageview的id
        imageView =(ImageView) findViewById(R.id.image_view);

        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.button1:
//                        逻辑控制
                        String inputText = editText.getText().toString();
                        Toast.makeText(MainActivity.this, inputText, Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }
        });

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageView.setImageResource(R.drawable.img1);
            }
        });
    }
}

 Effect:

                    After clicking - "       

4.3 Click the button to convert the image application

Requirements: Click the four buttons of spring, summer, autumn and winter in turn to display the corresponding four pictures 

layout file:

<?xml version="1.0" encoding="utf-8"?>

<!--最外层容器-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

<!--    放按钮-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/b1"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="春"/>

        <Button
            android:id="@+id/b2"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="夏"/>

        <Button
            android:id="@+id/b3"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="秋"/>

        <Button
            android:id="@+id/b4"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="冬"/>


    </LinearLayout>

<!--    放图片-->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <ImageView
            android:id="@+id/img1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/spring"
            android:scaleType="fitXY"/>
        <ImageView
            android:id="@+id/img2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/summer"
            android:visibility="invisible"
            android:scaleType="fitXY"/>
        <ImageView
            android:id="@+id/img3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/autumn"
            android:visibility="invisible"
            android:scaleType="fitXY"/>
        <ImageView
            android:id="@+id/img4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/winter"
            android:visibility="invisible"
            android:scaleType="fitXY"/>


    </FrameLayout>



</LinearLayout>

Activity file:

Three implementation methods of button's OnClickListener: 

(159 messages) Three implementation methods of button's OnClickListener_huiwolf2008's Blog-CSDN Blog

 The listener of the click event here is not the anonymous class new onClickListener, but the activity class implements the onClickListener interface, and then rewrites its corresponding method onclick.

package cn.edu.sdut.myclass831;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button b1,b2,b3,b4;
    ImageView img1,img2,img3,img4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         b1 = findViewById(R.id.b1);
         b2 = findViewById(R.id.b2);
         b3 = findViewById(R.id.b3);
         b4 = findViewById(R.id.b4);

         img1 = findViewById(R.id.img1);
         img2 = findViewById(R.id.img2);
         img3 = findViewById(R.id.img3);
         img4 = findViewById(R.id.img4);

        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
        b3.setOnClickListener(this);
        b4.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
//        获取点击的按钮的id值
        int id=view.getId();
//        首先隐藏所有图片
        hideImg();
        switch (id){
            case R.id.b1:
                img1.setVisibility(View.VISIBLE);
                break;
            case R.id.b2:
                img2.setVisibility(View.VISIBLE);
                break;
            case R.id.b3:
                img3.setVisibility(View.VISIBLE);
                break;
            case R.id.b4:
                img4.setVisibility(View.VISIBLE);
                break;
            default:
                break;

        }
    }

    protected void hideImg(){
        img1.setVisibility(View.INVISIBLE);
        img2.setVisibility(View.INVISIBLE);
        img3.setVisibility(View.INVISIBLE);
        img4.setVisibility(View.INVISIBLE);
    }

}

5. ProgressBar control

 5.1 Progress bar display in layout file

 <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

5.2 Click to make the progress bar appear/disappear

Properties of the control's three visible values: visible invisible gone

  •  Create a new progress bar object in the activity
  • Use findviewbyid to find the corresponding progress bar
  • Judging and setting the progress bar display or hide in the button click event
b3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(progressBar.getVisibility()==view.GONE)
                    progressBar.setVisibility(view.VISIBLE);
                else
                    progressBar.setVisibility(view.GONE);
            }
        });

5.3 Modify the progress bar style and progress

1. Modify the style and set the maximum range of the progress bar

  • The style attribute sets the horizontal progress bar
  • The max attribute sets the maximum value
<ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal"
        android:max="100"
        />

2. Click the button to increase the value of the progress bar

 Get the value of the progress bar through getProgress, and then click the button every time, the progress will increase by 10, and use setProgress to set the updated progress bar value.

b3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //            点击按钮设置可见性
//                if(progressBar.getVisibility()==view.GONE)
//                    progressBar.setVisibility(view.VISIBLE);
//                else
//                    progressBar.setVisibility(view.GONE);
                int prgress = progressBar.getProgress();
                prgress+=10;
                progressBar.setProgress(prgress);
            }
        });

 Effect:

Four, Dialog dialog box

Function: It is used to prompt the user for important content/information, and can block the interaction ability of other controls.

1. AlertDialog prompt information

The dialog does not need to be created in the layout file, but can be created directly in the event of clicking the button in the activity. The following template can be applied, and the specific method will not be explained again. 

b4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setTitle("这里有一条重要信息");
                dialog.setMessage("请注意休息,不要久坐哦~");
                dialog.setCancelable(false);
//              为对话框按钮创建点击事件
                dialog.setPositiveButton("好的", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
//                显示对话框
                dialog.show();
            }
        });

Effect:

4.2 Prompt message of ProgressDialog

A progress bar can appear in the dialog.

The method of use is similar to AlertDialog

b5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setTitle("加载进度");
                progressDialog.setMessage("正在加载中,请耐心等待~");
                progressDialog.setCancelable(true);
                progressDialog.show();
            }
        });

Effect:    

 

Guess you like

Origin blog.csdn.net/weixin_45662399/article/details/126496971