环境配置
- andriod Studio开发
各文件大致介绍
页面主要采用相对布局Relative Layout,方便居中
1、数据绑定与页面控制
通常给页面设置id,控制器声明再绑定
例如识别激活按钮的id为button,则其绑定以及点击事件方法如下
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView textView;
private TextView purl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init_View();
initBtnEvent();
}
//id绑定
private void Init_View(){
btn = findViewById(R.id.button);
textView = findViewById(R.id.textView);
purl = findViewById(R.id.url);
}
//按钮事件绑定
private void initBtnEvent(){
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//获取页面对应id元素的值
String text = purl.getText().toString();
//控制台打印语句
Log.e("激活码:",text);
//创建页面对应id元素的值
textView.setText("激活码输入成功");
}
});
}
}
2、正则匹配
每个字符是字母或数字,匹配六次
String code = "[A-Za-z0-9]{6}";
if (!purl.getText().toString().matches(code)){
textView.setText("格式不正确");
}
3、OkHttp的使用(get,post)
- manifest配置
允许网络访问,允许http低级别请求
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.garbage_sorting_andriod">
<!-- 允许网络访问 -->
<uses-permission android:name="android.permission.INTERNET" />
<!--默认要求需要加密的请求 即不可以用http 如果要用 需要android:usesCleartextTraffic="true"-->
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Garbage_sorting_andriod"
android:usesCleartextTraffic="true">
<activity
android:name=".HomeActivity"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
- 引入OkHttp
在build.gradle(注意有俩个,选字多的那个)文件的dependencies配置中加入语句:
implementation ‘com.squareup.okhttp3:okhttp:4.9.3’
(1)同步get方法
- 开线程处理。(又相当于异步了)
new Thread(){
@Override
public void run() {
try {
//第一步 创建request请求
Request request = new Request.Builder().url("https://***").build();
//第二步 得到Call对象
Call call = okHttpClient.newCall(request);
//第三步 执行Call的同步。得到response对象
Response response = call.execute();
String context response.body().string();
Log.e("context",context);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
- 线程中要改变layout的内容 需要添加
private Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
textView.setText(context);
}
});