2018-12-16 | UNLOCK

安卓期末复习资料


02.checkbox 改变事件

1
2
3
4
5
6
7
8
9
10
CB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked){
example2.setVisibility(View.VISIBLE);
}else{
example2.setVisibility(View.GONE);
}
}
});

03.Toast 提示框

1
Toast.makeText(this, "输入格式有误,重新输入!", Toast.LENGTH_LONG).show();

04.下拉框选中了哪个

1
2
3
4
5
6
7
8
9
10
11
12
int itemPos = spnYsf.getSelectedItemPosition();
double result=0;
switch (itemPos){
case 0:
result=num1+num2;break;
case 1:
result=num1-num2;break;
case 2:
result=num1*num2;break;
case 3:
result=num1/num2;break;
}

05.radioButton 组 选中了哪个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
switch (RG.getCheckedRadioButtonId()){
case R.id.rdb1:
tvResult.setText(String.format("%.0f",result));
break;
case R.id.rdb2:
tvResult.setText(String.format("%f",result));
break;
case R.id.rdb3:
tvResult.setText(String.format("%.3f",result));
break;
default:
tvResult.setText(String.format("%.3f",result));
break;
}

06.截取 float 的后三位小数点

1
String.format("%.3f", result)

07.dialog 和自定义菜单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
//return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
//return super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.item_about:
//
AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setMessage("This calculator is made by ROT.");
builder.setTitle("About");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText( MainActivity.this, " \"OK\" was clicked", Toast.LENGTH_LONG).show();
}
});
builder.create().show();
break;
case R.id.item_exit:
this.finish();
break;
}
return true;
}

布局文件 layout

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2">

<EditText
android:id="@+id/editNum1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:ems="10"
/>

<Spinner
android:id="@+id/spinner"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>

<EditText
android:id="@+id/editNum2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:ems="10"
/>


</LinearLayout>
<Button
android:id="@+id/buttoncalc"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:text="计算" />
<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/rdb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示整数"/>
<RadioButton
android:id="@+id/rdb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示小数"/>
<RadioButton
android:id="@+id/rdb3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示到小数点后三位"/>
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="结果"
android:textSize="30dp"
android:textColor="#000"/>
<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<CheckBox
android:id="@+id/CheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="高级计算"/>

<LinearLayout
android:id="@+id/example2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="gone"
android:layout_weight="1">

<Spinner
android:id="@+id/danmuSpinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"></Spinner>

<EditText
android:id="@+id/danmuNum"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>

<Button
android:id="@+id/danmuClick"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="计算"
android:layout_weight="1"
android:onClick="danmuClick"/>

<TextView
android:id="@+id/danmuResult"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="结果"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>

08.IO 文件读操作模拟登陆验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//读取流
FileInputStream fis;
String fileName="userInfo.txt";
String content="";
String [] userInfo= null;

try {
fis=openFileInput(fileName);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
content=new String(buffer);
userInfo=content.split(",");
// Toast.makeText(LoginActivity.this, ""+userInfo[0]+ userInfo[1], Toast.LENGTH_LONG).show();
username=userInfo[0];
password=userInfo[1];
}
catch (Exception e){
Toast.makeText(LoginActivity.this, ""+e, Toast.LENGTH_LONG).show();

}

09.判断是否为空

1
if(inputPwd.getText().toString().trim().equals(""))

10.记住密码案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//记住密码
SharedPreferences sp = getSharedPreferences("userdata",MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (rePwd.isChecked()){
editor.putString("name", inputUsn.getText().toString().trim());
editor.putString("pwd", inputPwd.getText().toString().trim());
editor.putBoolean("isRemember", true);
}
else{
//如果没有记住密码,那么将所有值设置为空。
editor.putString("name", null);
editor.putString("pwd", null);
editor.putBoolean("isRemember", false);
}
editor.commit();//提交

11.结束本窗口

1
LoginActivity.this.finish();

12.跳转窗口并传值

1
2
3
4
5
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("name", inputUsn.getText().toString().trim());
intent.putExtras(bundle);
startActivity(intent);

13.直接跳转

1
2
Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
startActivity(intent);

14.窗口初始化的时候判断是否要记住密码

1
2
3
4
5
6
7
8
9
10
11
12
//如果记住密码 就初始化 账户密码 并设置checkbox选中状态
SharedPreferences sp = getSharedPreferences("userdata", MODE_PRIVATE);
Boolean remember = sp.getBoolean("isRemember", false); //false 为缺省值
if (remember){
rePwd.setChecked(true);
String name=sp.getString("name", null);
String pwd=sp.getString("pwd", null);
inputUsn.setText(name);
inputPwd.setText(pwd);
}else{
rePwd.setChecked(false);
}

15.IO 流模拟注册过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//写入流
String fileName="userInfo.txt";
String splitStr=",";
FileOutputStream fos;
try {
fos=openFileOutput(fileName,MODE_PRIVATE);
fos.write(usn.getBytes());
fos.write(splitStr.getBytes());
fos.write(pwd1.getBytes());
fos.write(splitStr.getBytes());
fos.write(phone.getBytes());
fos.write(splitStr.getBytes());
fos.write(email.getBytes());
fos.close();
}
catch (Exception e){
Toast.makeText(RegisterActivity.this, ""+e, Toast.LENGTH_LONG).show();
}

Toast.makeText(RegisterActivity.this, "恭喜!注册成功!", Toast.LENGTH_SHORT).show();
RegisterActivity.this.finish();//结束当前页面

16.获取跳转过来的传值

1
2
3
4
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
name = bundle.getString("name");
tvInfo.setText(name+",欢迎来到Android考试系统!");

17.关闭 APP

1
System.exit(0);

18.答题页结束返回主界面 判断是否回答正确

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==1){
if(resultCode==1){
if(data.getStringExtra("key").equals("B")){
tvInfo.setText(name+",欢迎来到Android考试系统!\n答案正确!");
}
else
{
tvInfo.setText(name+",欢迎来到Android考试系统!\n答案错误!可以返回重新作答。");
}
}
}
}

19.答题界面,答题按钮事件,答题结束后返回主页面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
String key="";
switch (chooseGroup.getCheckedRadioButtonId()){
case R.id.item1:
key="A";
break;
case R.id.item2:
key="B";
break;
case R.id.item3:
key="C";
break;
case R.id.item4:
key="D";
break;
default:
Toast.makeText(AnwserActivity.this, "未选择答案!", Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent();
intent.putExtra("key",key);
setResult(1,intent);
AnwserActivity.this.finish();

20.绑定控件的时候推荐写一个函数 init()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
MyHelper myHelper;
private Button insertBtn,deleteBtn,updateBtn,selectBtn;
private EditText editName,editPhone;
private TextView showResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myHelper = new MyHelper(this);
init();
}

private void init(){
insertBtn = (Button)findViewById(R.id.insertBtn);
deleteBtn = (Button)findViewById(R.id.deleteBtn);
updateBtn = (Button)findViewById(R.id.updateBtn);
selectBtn = (Button)findViewById(R.id.selectBtn);
editName = (EditText)findViewById(R.id.editName);
editPhone = (EditText)findViewById(R.id.editPhone);
showResult= (TextView)findViewById(R.id.showText);
}

21.模拟 curd 操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public void OnClick(View v){
String name,phone;
SQLiteDatabase db;
ContentValues values;
switch (v.getId()){
case R.id.insertBtn: //插入新数据
name = editName.getText().toString().trim();
phone = editPhone.getText().toString().trim();
db = myHelper.getWritableDatabase();
values = new ContentValues();
values.put("name", name);
values.put("phone", phone);
db.insert("information", null, values);
Toast.makeText(this, "信息已添加", Toast.LENGTH_SHORT).show();
db.close();
break;
case R.id.selectBtn://查询所有数据
db = myHelper.getReadableDatabase();
Cursor cursor = db.query("information", null, null, null, null, null, null);
if(cursor.getCount()==0){
showResult.setText("");
Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
}else{
cursor.moveToFirst();
showResult.setText("姓 名 :"+cursor.getString(1)+" ; 电 话 :"+cursor.getString(2));
}
while(cursor.moveToNext()){
showResult.append("\n"+"姓 名 :"+cursor.getString(1)+" ; 电 话 :"+cursor.getString(2));
}
cursor.close();
db.close();
break;
case R.id.updateBtn://更新指定数据
db = myHelper.getWritableDatabase();
values = new ContentValues();
values.put("phone",phone = editPhone.getText().toString().trim());
db.update("information", values, "name=?", new String[]{editName.getText().toString().trim()});
Toast.makeText(this, "信息已修改", Toast.LENGTH_SHORT).show();
db.close();
break;
case R.id.deleteBtn://清空所有数据
db = myHelper.getWritableDatabase();
db.delete("information", null, null);
Toast.makeText(this, "信息已删除", Toast.LENGTH_SHORT).show();
showResult.setText("");
db.close();
break;
}
}

22.Myhelper 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MyHelper extends SQLiteOpenHelper{
public MyHelper(Context context){
super(context,"itcast.db",null,1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE information(_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),phone VARCHAR(20))");
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}
}

23.跳转窗口并传递多个参数

1
2
3
4
5
6
7
Intent intent = new Intent(MainActivity.this,InfoActivity.class);
Bundle bundle = new Bundle();
bundle.putString("usn", usn);
bundle.putString("pwd", pwd);
bundle.putString("sex", sexInfo);
intent.putExtras(bundle);
startActivity(intent);

24.打开浏览器跳转百度

1
2
3
4
5
//打开浏览器,百度网站
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent);

25.AndroidManifest.xml 修改页面标题

1
android:label="用户登录"

26.AndroidManifest.xml 设置某个页面为主页

1
2
3
4
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

27.IO 写操作模拟注册

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//写入流
String fileName="userInfo.txt";
String splitStr=",";
FileOutputStream fos;
try {
fos=openFileOutput(fileName,MODE_PRIVATE);
fos.write(usn.getBytes());
fos.write(splitStr.getBytes());
fos.write(pwd1.getBytes());
fos.write(splitStr.getBytes());
fos.write(phone.getBytes());
fos.write(splitStr.getBytes());
fos.write(email.getBytes());
fos.close();
}
catch (Exception e){
Toast.makeText(RegisterActivity.this, ""+e, Toast.LENGTH_LONG).show();
}

Toast.makeText(RegisterActivity.this, "恭喜!注册成功!", Toast.LENGTH_SHORT).show();

28.弹出通知栏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//弹出通知
PendingIntent pendingIntent = PendingIntent.getActivity(
MainActivity.this,
0,
new Intent(MainActivity.this, MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);

NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

if(Build.VERSION.SDK_INT >= 26)
{
//当sdk版本大于26
String id = "channel_1";
String description = "143";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(id, description, importance);
// channel.enableLights(true);
// channel.enableVibration(true);//
manager.createNotificationChannel(channel);
Notification notification = new Notification.Builder(MainActivity.this, id)
.setCategory(Notification.CATEGORY_MESSAGE)
.setSmallIcon(android.R.drawable.star_on)
.setLargeIcon(BitmapFactory.decodeResource(MainActivity.this.getResources(),R.drawable.stars))
.setTicker("我的计算器")
.setContentTitle("计算结果")
.setContentText(String.format("%.5f", ope3))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.build();
manager.notify(1, notification);
}
else
{
//当sdk版本小于26
Notification notification = new Notification.Builder(MainActivity.this)
.setSmallIcon(android.R.drawable.star_on)
.setLargeIcon(BitmapFactory.decodeResource(MainActivity.this.getResources(),R.drawable.stars))
.setTicker("我的计算器")
.setContentTitle("计算结果")
.setContentText(String.format("%.5f", ope3))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.build();
manager.notify(1,notification);
}

29.UserInfo 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class UserInfo {
private Long id;
private String username,password;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public UserInfo(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}

public UserInfo() {

}

public UserInfo(String username, String password) {
this.username = username;
this.password = password;
}
}

30.UserDao 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.example.administrator.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


public class UserDao {
private MyHelper helper;

public UserDao(Context context) {
helper = new MyHelper(context);
}

public void insert(UserInfo user) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("username", user.getUsername());
values.put("password", user.getPassword());
long id = db.insert("user", null, values);
user.setId(id);
db.close();
}

public int delete(long id) {
SQLiteDatabase db = helper.getWritableDatabase();
int count = db.delete("user", "_id=?", new String[]{id + ""});
db.close();
return count;
}

public int update(UserInfo user) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("username", user.getUsername());
values.put("password", user.getPassword());
int count = db.update("user", values, "_id=?", new String[]{user.getId() + ""});
db.close();
return count;
}


public String selectPwd(String username) {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.query("user", null, "username=?", new String[]{username}, null, null, null);

String pwd="";
if (c.getCount()==0){
pwd="";
}
else{
c.moveToFirst();
pwd=c.getString(2);
}
c.close();
db.close();
return pwd;
}
}

31.Myhelper 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.example.administrator.myapplication;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyHelper extends SQLiteOpenHelper {
public MyHelper(Context context) {
super(context, "userInfo.db", null, 2);
}

public void onCreate(SQLiteDatabase db) {
System.out.println("onCreate");
db.execSQL("CREATE TABLE user(_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "username VARCHAR(20)," +
"password VARCHAR(50))");
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("onUpgrade");
}
}

32.模拟注册插入新数据

1
2
3
4
UserInfo userInfo = new UserInfo(inputUsn.getText().toString().trim(),inputPwd1.getText().toString().trim());
UserDao userDao = new UserDao(RegisterActivity.this);
userDao.insert(userInfo);
Toast.makeText(RegisterActivity.this, "恭喜!数据库插入成功!", Toast.LENGTH_SHORT).show();

33.模拟登陆 获取密码对比

1
2
3
4
5
6
7
8
9
10
11
12
username = inputUsn.getText().toString().trim();
UserDao userDao = new UserDao(LoginActivity.this);
password = userDao.selectPwd(username);
if (inputPwd.getText().toString().trim().equals("")
|| inputUsn.getText().toString().trim().equals("")) {
Toast.makeText(LoginActivity.this, "信息未填写完整!", Toast.LENGTH_SHORT).show();
} else if (password.equals("")) {
Toast.makeText(LoginActivity.this, "用户名不存在!", Toast.LENGTH_SHORT).show();
return;
} else if (inputPwd.getText().toString().trim().equals(password)) {
Toast.makeText(LoginActivity.this, "验证通过,登录成功!", Toast.LENGTH_SHORT).show();
//.............}

以上复习资料,仅供参考