Android development notes for back-end engineers getting started (1)

background summary

I am daxia, a back-end developer who has been working for more than 8 years. The front-end has been limited to Web page development, and I have basically zero foundation in mobile terminal development and small program development. Mobile phone support is not ideal now. I took a break to learn Android, and made a note of some key content that I think. I also hope that the notes can be helpful to others.

1. Development steps

Write the interface first -> then write the logic of the Activity. Regardless of the style of the interface, just care about the interactive elements you need.

Layout sample code, generally use LinearLayout layout, LinearLayout layout has vertical layout and horizontal layout, there must be android:orientation="vertical"this line of code in the main.xml 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"
    >

    <EditText
        android:id="@+id/login_input_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入你的用户名" />

</LinearLayout>

2. Click event

  1. Introduce a package that listens to events
  2. You need to set an ID for the button button in xml
  3. Find the ID in the controller and set a listening event
  4. Then implement onClickthe method
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button login_btn_submit;
    
        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //找到对应元素
        login_btn_submit = findViewById(R.id.login_btn_submit);
        //设置监听事件
        login_btn_submit.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.login_btn_submit) {
            userLogin();
        }
    }

3. Jump between activities and data transfer

3.1 Jump page

First get the value content, and then use Intent to jump, see the sample code for details

//执行用户登录
    protected void userLogin() {

        Intent intent = new Intent();
        intent.putExtra("username", login_input_username.getText());
        intent.putExtra("password", login_input_password.getText());
        intent.setClass(MainActivity.this, UserList.class);
        startActivity(intent);
    }

3.2 Receive data

B page receives data

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_list);
        try {
            Intent intent = getIntent();
            userId = intent.getExtras().getString("user_id");
            Log.i(getLocalClassName(), "22222____" + userId);
        } catch (NullPointerException e) {
            Toast.makeText(this, "user_id is null", Toast.LENGTH_LONG).show();
        }

        initView();
    }

4. List page layout

4.1 Create a new subpage

Create a new xml for the layout of each row

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

    <TextView
        android:id="@+id/user_item_name"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:text="11" />

    <TextView
        android:id="@+id/user_item_age"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:text="11" />

    <ImageView
        android:id="@+id/user_item_pic"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:src="@mipmap/touxiang" />

</LinearLayout>

4.2 Prepare data

Create a new data structure object and determine the data format

Three variables are defined, and the corresponding access method can be automatically generated by the editor's generation function

package site.qingscan.qingting;

import java.io.Serializable;

public class Account implements Serializable {

    private String name;
    private int age;
    private int pic;
}

4.3 Data adaptation

Create a new adapter

Render the page and data

package site.qingscan.qingting;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

public class UserListAdapter extends BaseAdapter {
    private List<Account> userList;
    private Context context;

    public UserListAdapter(List<Account> userList,Context context) {
        this.userList = userList;
        this.context = context;
    }

    @Override
    public int getCount() {
        return userList.size();
    }

    @Override
    public Object getItem(int i) {
        return userList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        //找到页面
        LinearLayout layout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.user_list_item, null);
        //找到对应元素
        TextView user_item_name = (TextView) layout.findViewById(R.id.user_item_name);
        TextView user_item_age = (TextView) layout.findViewById(R.id.user_item_age);
        ImageView user_item_pic = layout.findViewById(R.id.user_item_pic);
        //给元素赋值
        user_item_name.setText(userList.get(i).getName());
        user_item_age.setText(Integer.toString(userList.get(i).getAge()));
        user_item_pic.setImageResource(userList.get(i).getPic());
        //返回对象
        return layout;
    }
}

4.4 Combined calls

call in activity

private void initView() {
        user_list = findViewById(R.id.userlist_list);
        ArrayList<Account> users = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            Account tempObj = new Account();
            tempObj.setName("tqs" + Integer.toString(i));
            tempObj.setAge(25 + i);
            tempObj.setPic(R.mipmap.touxiang);
            users.add(tempObj);
        }

        user_list.setAdapter(new UserListAdapter(users,this));

    }

5. Network request

5.1 POST request

First define a function for sending HTTP packets, the code is as follows

public String httpLoginRequest(String username, String psd) {
        String msg = "";    //服务器返回结果
        try {
            URL url = new URL(loginUrlZhuCe);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.connect();
            //post请求传递参数
            String data = "uname=" + username + "&psd=" + psd;   //参数之间用&连接
            //向服务器发送数据(输出流)
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
            writer.write(data);
            writer.close();

            //接受服务器反馈信息
            int code = httpURLConnection.getResponseCode();  //获得服务器反馈信息
            Log.d("login", "" + code);
            if (code == HttpURLConnection.HTTP_OK) {
                //接收服务器返回信息(输入流)
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                String line = "";
                //使用循环来获得数据,一次一行
                while ((line = reader.readLine()) != null) {
                    msg += line;
                }
                Log.d("login", "msg:" + msg);
                reader.close();  //关闭
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    } //end login

5.2 Sub-thread call

Network requests cannot be executed in the main thread, and a new thread needs to be created

protected void userLogin() {

        new Thread(new Runnable() {
            public void run() {
                httpLoginRequest("dddd", "bbb");
            }
        }).start();
        
    }

It should be noted that access to the network requires permission

In AndroidManifest.xmlthe file <manifest>tag add

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

Author: Tang Qingsong

Date: June 28, 2022

Guess you like

Origin blog.csdn.net/u013431141/article/details/125525532