background abstract
I'm daxia, a back-end developer who has been developing for more than 8 years. The front-end development has always been limited to web page development, and has basically zero foundation for mobile terminal development and applet development. Sometimes I want to do something interesting and use web pages to achieve Mobile phone support is not ideal now. I learned to learn Android while I was busy, and I made a note on some of the important content, and I hope that the note will be helpful to others.
1. Development steps
First write the interface -> and then write the logic of the Activity. Don't care about the style of the interface, just care about the interactive elements you need.
Layout example code, generally use LinearLayout layout, LinearLayout layout has vertical layout and horizontal layout, the main.xml file must have android:orientation="vertical"
this line of code
<?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
- Introduce a package that listens for events
- Need to set an ID for the button button in xml
- Find the ID in the controller, set a listener event
- Then implement the
onClick
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 and data transfer between activities
3.1 Jump page
First get the value content, and then use the 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
Page B 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();
}
Fourth, the 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 generation function of the editor
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 Child 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 additional permissions
Add the <manifest>
tag in the AndroidManifest.xml
file
<uses-permission android:name="android.permission.INTERNET" />
Author: Tang Qingsong
Date: June 28, 2022
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。