Android开发经验总结
温馨提示:下文是博主在Android开发过程中,对常见部分问题进行的方法总结与经验杂谈,希望大家多多支持!!!
文章目录
一、针对高版本API进行网络访问
1.打开网络权限
<uses-permission android:name="android.permission.INTERNET" />
2.网络权限文件配置
(1)XML文件
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true"/>
</network-security-config>
(2)文件放置位置
(3)清单文件引用
3.网络框架及数据解析包的导入
(1)网络请求的封装
package com.fjzzy.pzc.utils;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import java.io.IOException;
/**
* @author pzc
* requestHttp 网络请求
* address 请求地址后缀
* jsonData 请求参数
* isToken 是否携带Token
* isType 请求类型
* tClass 实体类
*/
public class OkHttpUtils {
static final OkHttpClient CLIENT = new OkHttpClient();
static final String URL="";
static final String TOKEN="";
public static <T> T requestHttp(String address, String jsonData, boolean isToken, String isType, Class<T> tClass) throws IOException {
synchronized (CLIENT) {
RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonData);
Request request = new Request.Builder()
.url(URL + address)
.build();
if (isToken) {
request.newBuilder().addHeader("替换你需要的Header", TOKEN);
}
switch (isType) {
case "GET":
request.newBuilder().get();
break;
case "POST":
request.newBuilder().post(body);
break;
case "PUT":
request.newBuilder().put(body);
break;
default:
}
return new Gson().fromJson(CLIENT.newCall(request).execute().body().string(), tClass);
}
}
}
二、利用Collections进行数据排序
(1)创建Enity类DataBean
package com.fjzzy.pzc.enity;
public class DateBean {
public DateBean(int id, int num, String startTime, String endTime) {
this.id = id;
this.num = num;
this.startTime = startTime;
this.endTime = endTime;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
int id;
int num;
String startTime;
String endTime;
}
(2)初始化并写入DataBean
List<DateBean> list;
list = new ArrayList<>();
list.add(new DateBean(1, 22, "2020-11-06", "2020-11-18"));
list.add(new DateBean(2, 44, "2020-11-02", "2020-11-13"));
list.add(new DateBean(3, 88, "2020-11-08", "2020-11-14"));
list.add(new DateBean(4, 66, "2020-11-03", "2020-11-16"));
list.add(new DateBean(5, 11, "2020-11-05", "2020-11-17"));
list.add(new DateBean(6, 66, "2020-11-06", "2020-11-12"));
list.add(new DateBean(7, 33, "2020-11-01", "2020-11-19"));
(3)ListView对数据源进行输出
listView.setAdapter(adapter);
class MyAdapter extends BaseAdapter{
public MyAdapter(List<DateBean> data) {
this.data = data;
backData = data;
}
List<DateBean> data; //这个数据是会改变的,所以要有个变量来备份一下原始数据
List<DateBean> backData;//用来备份原始数据
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
@SuppressLint("ViewHolder")
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, null);
ViewHolder viewHolder = new ViewHolder(view);
viewHolder.tvId.setText(String.valueOf(data.get(position).getId()));
viewHolder.tvNum.setText(String.valueOf(data.get(position).getNum()));
viewHolder.tvsTime.setText(String.valueOf(data.get(position).getStartTime()));
viewHolder.tveTime.setText(String.valueOf(data.get(position).getEndTime()));
return view;
}
class ViewHolder {
TextView tvId, tvNum, tvsTime, tveTime;
View rootView;
public ViewHolder(View rootView) {
this.rootView = rootView;
tvId = rootView.findViewById(R.id.tv_id);
tvNum = rootView.findViewById(R.id.tv_num);
tvsTime = rootView.findViewById(R.id.tv_startTime);
tveTime = rootView.findViewById(R.id.tv_endTime);
}
}
}
附:1.ListView绑定的布局
<?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"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center">
<TextView
android:id="@+id/tv_id"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="1"
android:textSize="20dp" />
<TextView
android:id="@+id/tv_num"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="1"
android:textSize="20dp" />
<TextView
android:id="@+id/tv_startTime"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:gravity="center"
android:text="1"
android:textSize="20dp" />
<TextView
android:id="@+id/tv_endTime"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:gravity="center"
android:text="1"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
附:2.主界面布局
<?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"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<EditText
android:id="@+id/edit_select"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"/>
<Button
android:id="@+id/btn_select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#fff"
android:text="搜索"
android:textSize="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<Button
android:id="@+id/btn_selectUp"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="up"/>
<Button
android:id="@+id/btn_selectDown"
android:layout_marginLeft="20dp"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="down"/>
</LinearLayout>
<Button
android:id="@+id/btn_selectTime"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="按时间排序"/>
<ListView
android:id="@+id/list_View"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
(4)进行排序
1.升序
btnSelectUp.setOnClickListener((v) -> {
Collections.sort(list, new MaxNum());
///数据显示
listView.setAdapter(new MyAdapter(list));
});
///排序的方法
static class MaxNum implements Comparator {
@Override
public int compare(Object o1, Object o2) {
DateBean bean = (DateBean) o1;
DateBean thisBean = (DateBean) o2;
return Integer.compare(bean.getId() & bean.getNum(), thisBean.getId() & thisBean.getNum());
}
}
2.降序
btnSelectDown.setOnClickListener((v) -> {
Collections.reverse(list);
listView.setAdapter(new MyAdapter(list));
});
三、对ListView进行Filter过滤
1.该过滤基于上述操作
package com.fjzzy.pzc;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.fjzzy.pzc.enity.DateBean;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
/**
* @author pzc
*/
public class MainActivity extends BaseActivity {
List<DateBean> list;
List<DateBean> updateList;
ListView listView;
EditText editText;
Button btnSelect, btnSelectUp, btnSelectDown, btnSelectTime;
private static final String TAG = "MainActivity";
BaseAdapter adapter;
String text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected int getLayout() {
return R.layout.activity_main;
}
@Override
protected void initView() {
list = new ArrayList<>();
updateList = new ArrayList<>();
listView = findViewById(R.id.list_View);
//开启过滤
listView.setTextFilterEnabled(true);
editText = findViewById(R.id.edit_select);
btnSelect = findViewById(R.id.btn_select);
btnSelectUp = findViewById(R.id.btn_selectUp);
btnSelectDown = findViewById(R.id.btn_selectDown);
btnSelectTime = findViewById(R.id.btn_selectTime);
}
@Override
protected void initData() {
@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
Date date = new Date();
date.getTime();
String format = simpleDateFormat.format(date);
Log.d(TAG, "initData: " + format);
list.add(new DateBean(1, 22, "2020-11-06", "2020-11-18"));
list.add(new DateBean(2, 44, "2020-11-02", "2020-11-13"));
list.add(new DateBean(3, 88, "2020-11-08", "2020-11-14"));
list.add(new DateBean(4, 66, "2020-11-03", "2020-11-16"));
list.add(new DateBean(5, 11, "2020-11-05", "2020-11-17"));
list.add(new DateBean(6, 66, "2020-11-06", "2020-11-12"));
list.add(new DateBean(7, 33, "2020-11-01", "2020-11-19"));
adapter = new MyAdapter(list);
listView.setAdapter(adapter);
}
@Override
protected void clickEvent() {
btnSelect.setOnClickListener((v -> {
text = editText.getText().toString().trim();
if (TextUtils.isEmpty(text)) {
//搜索文本为空时,过滤设置
listView.clearTextFilter();
text = null;
runOnUiThread(() -> {
listView.setAdapter(new MyAdapter(list));
});
} else {
//设置过滤关键字
listView.setFilterText(text);
}
}));
btnSelectUp.setOnClickListener((v) -> {
if (text != null) {
Collections.sort(updateList, new MaxNum());
} else {
Collections.sort(list, new MaxNum());
}
runOnUiThread(() -> {
if (text != null) {
listView.setAdapter(new MyAdapter(updateList));
} else {
listView.setAdapter(new MyAdapter(list));
}
});
});
btnSelectDown.setOnClickListener((v) -> {
if (text != null) {
Collections.sort(updateList, new MinMum());
} else {
Collections.sort(list, new MinMum());
}
// Collections.reverse(list);
runOnUiThread(() -> {
if (text != null) {
listView.setAdapter(new MyAdapter(updateList));
} else {
listView.setAdapter(new MyAdapter(list));
}
});
});
}
static class MaxNum implements Comparator {
@Override
public int compare(Object o1, Object o2) {
DateBean bean = (DateBean) o1;
DateBean thisBean = (DateBean) o2;
return Integer.compare(bean.getId() & bean.getNum(), thisBean.getId() & thisBean.getNum());
}
}
static class MinMum implements Comparator {
@Override
public int compare(Object o1, Object o2) {
DateBean bean = (DateBean) o1;
DateBean thisBean = (DateBean) o2;
return Integer.compare(thisBean.getNum(), bean.getNum());
}
}
@Override
public void onClick(View v) {
}
class MyAdapter extends BaseAdapter implements Filterable {
public MyAdapter(List<DateBean> data) {
this.data = data;
backData = data;
}
List<DateBean> data; //这个数据是会改变的,所以要有个变量来备份一下原始数据
List<DateBean> backData;//用来备份原始数据
MyFilter mFilter;
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
@SuppressLint("ViewHolder")
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, null);
ViewHolder viewHolder = new ViewHolder(view);
viewHolder.tvId.setText(String.valueOf(data.get(position).getId()));
viewHolder.tvNum.setText(String.valueOf(data.get(position).getNum()));
viewHolder.tvsTime.setText(String.valueOf(data.get(position).getStartTime()));
viewHolder.tveTime.setText(String.valueOf(data.get(position).getEndTime()));
return view;
}
@Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new MyFilter();
}
return mFilter;
}
class ViewHolder {
TextView tvId, tvNum, tvsTime, tveTime;
View rootView;
public ViewHolder(View rootView) {
this.rootView = rootView;
tvId = rootView.findViewById(R.id.tv_id);
tvNum = rootView.findViewById(R.id.tv_num);
tvsTime = rootView.findViewById(R.id.tv_startTime);
tveTime = rootView.findViewById(R.id.tv_endTime);
}
}
class MyFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
List<DateBean> list;
if (TextUtils.isEmpty(constraint)) {
//当过滤的关键字为空的时候,我们则显示所有的数据
list = backData;
} else {
//否则把符合条件的数据对象添加到集合中
list = new ArrayList<>();
for (DateBean str : backData) {
if (str.getStartTime().contains(constraint) || str.getEndTime().contains(constraint)) {
Log.d(TAG, "performFiltering:" + str.toString());
list.add(str);
}
}
}
result.values = list; //将得到的集合保存到FilterResults的value变量中
result.count = list.size();//将集合的大小保存到FilterResults的count变量中
return result;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
data = (List<DateBean>) results.values;
updateList = data;
Log.d(TAG, "publishResults:" + results.count);
if (results.count > 0) {
notifyDataSetChanged();
Log.d(TAG, "数据发生了改变");
} else {
notifyDataSetInvalidated();
Log.d(TAG, "数据失效");
}
}
}
}
}
四、用独特的Activity玩Android
BaseActivity
package com.fjzzy.pzc;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
/**
* @author pzc
*/
public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {
public void initToolBar(TextView textView, Toolbar toolbar, boolean homeAsUpEnabled, String title) {
textView.setText(title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(homeAsUpEnabled);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayout());
initView();
initData();
clickEvent();
}
//fragment逐个退出
@Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
}
protected abstract int getLayout();
protected abstract void initView();
protected abstract void initData();
protected abstract void clickEvent();
}
五、插件如何让Android与代码爱不释手
1.Alibaba Java coding Guidelines
阿里巴巴Java开发手册
2.OK, Gradle!
添加插件的利器
3.Rainbow Brackets
彩虹括号
4.activate-power-mode
IDEA的花式输入
去掉烦人的字母
5.GsonFormat
直接把json数据转换为实体类
六、对轻量级数据存储进行封装
package com.fjzzy.pzc.utils;
import android.content.Context;
import android.content.SharedPreferences;
/**
* @author pzc
* context 上下文
* shared 轻量级数据存储
* fileName 文件名
* key,data key,unData 键值对
* isSave 不存则读
*/
public class SharedUtils {
public static String shared(Context context,String fileName,String key,String data,String unData,boolean isSave){
SharedPreferences preferences=context.getSharedPreferences(fileName,Context.MODE_PRIVATE);
if (isSave){
preferences.edit().putString(key, data).apply();
return "save success";
}else {
return preferences.getString(key,unData);
}
}
}
七、如何搭建一个Fluutter项目
1.获取Flutter SDK
2.安装Flutter SDK
(1)载好的文件博主放在的是E盘
(2)载好后会多出如下文件
3.AS安装Flutter插件
4.配置环境变量
(1)编辑用户变量
FLUTTER_STORAGE_BASE_URL
https://storage.flutter-io.cn
PUB_HOSTED_URL
https://pub.flutter-io.cn
(2)编辑系统变量
E:\Flutter\flutter-1.24.0-10.2.pre\bin
E:\Flutter\flutter-1.24.0-10.2.pre\bin\cache\dart-sdk\bin
E:\Git\cmd
E:\Git\bin
E:\Git\mingw64\libexec\git-core
5.安装Flutter
Win键+R
输入cmd
6.创建Flutter项目
总结
提示:把以前的开发经验整理分享出来,希望大家多多支持、指正呀!
此文原创、未经允许、不可转载!!!
博主QQ:691828516 学生党12小时 在线+。+
微信:IU_lost_child 你没看错 博主喜欢的是iu!!!
再次感谢大家的赏析!!!
转载:https://blog.csdn.net/Hdrosay/article/details/109800324
查看评论