1、开发一个APP,程序运行后的界面如下
设计一个APP,运行时显示第1个界面。点击“计算”按钮,显示第2个界面,并将第1数、第2个数的和显示在第2个界面中。点击“返回”按钮,返回到第1个界面
代码:
OneActivity.java
package top.yh.homework.one;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import top.yh.homework.R;
import top.yh.homework.util.StringUtil;
import top.yh.homework.util.ViewUtil;
public class OneActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
final OneActivity that = this;
EditText etOne = findViewById(R.id.et_one);
EditText etTwo = findViewById(R.id.et_two);
TextView tvRes = findViewById(R.id.tv_res);
Button btnCal = findViewById(R.id.btn_cal);
ActivityResultLauncher<Intent> register =
registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
Intent intent = result.getData();
if (intent == null || result.getResultCode() != RESULT_OK) {
return;
}
tvRes.setText(intent.getStringExtra("result"));
});
btnCal.setOnClickListener(view -> {
String one = etOne.getText().toString().trim();
String two = etTwo.getText().toString().trim();
if (StringUtil.isEmpty(one) || StringUtil.isEmpty(two)) {
//为空
ViewUtil.showToast(that, "请输入数据!");
return;
}
register.launch(new Intent(that, ResultActivity.class).putExtra("one", one)
.putExtra("two", two));
});
}
}
activity_one.xml
<?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="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".one.OneActivity">
<LinearLayout
android:layout_marginBottom="40dp"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/translucent_text_view"
android:text="@string/one_one_number"
android:layout_marginEnd="50dp"
android:textSize="25sp" />
<EditText
android:id="@+id/et_one"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:inputType="number"
android:background="@drawable/edit_text_selector"
android:autofillHints="" />
</LinearLayout>
<LinearLayout
android:layout_marginBottom="40dp"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/translucent_text_view"
android:text="@string/one_two_number"
android:layout_marginEnd="50dp"
android:textSize="25sp" />
<EditText
android:id="@+id/et_two"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:inputType="number"
android:background="@drawable/edit_text_selector"
android:autofillHints="" />
</LinearLayout>
<LinearLayout
android:layout_marginBottom="40dp"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="@drawable/translucent_text_view"
android:text="@string/one_result"
android:gravity="center"
android:layout_marginEnd="50dp"
android:textSize="25sp" />
<TextView
android:id="@+id/tv_res"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/edit_text_selector"/>
</LinearLayout>
<Button
android:id="@+id/btn_cal"
android:layout_marginTop="20dp"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:background="@drawable/translucent_text_view"
android:text="@string/one_cal"
android:textSize="25sp"/>
</LinearLayout>
ResultActivity.java
package top.yh.homework.one;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import top.yh.homework.R;
import top.yh.homework.util.ViewUtil;
public class ResultActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
final ResultActivity that = this;
Intent intent = getIntent();
if (intent == null) {
ViewUtil.showToast(that,"没有接收到数据");
return;
}
String one = intent.getStringExtra("one");
String two = intent.getStringExtra("two");
String res = (Integer.parseInt(one) + Integer.parseInt(two)) + "";
TextView tvRes = findViewById(R.id.tv_res);
tvRes.setText(res);
findViewById(R.id.btn_back).setOnClickListener(view -> {
//返回上一页面
setResult(RESULT_OK,new Intent().putExtra("result",res));
finish();
});
}
}
activity_result.xml
<?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="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
tools:context=".one.ResultActivity">
<LinearLayout
android:layout_width="350dp"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="50dp"
android:background="@drawable/translucent_text_view"
android:gravity="center"
android:text="@string/one_result"
android:textSize="25sp" />
<TextView
android:id="@+id/tv_res"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/edit_text_selector" />
</LinearLayout>
<Button
android:id="@+id/btn_back"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="@drawable/translucent_text_view"
android:text="@string/one_back"
android:textSize="25sp" />
</LinearLayout>
2、设计APP,运行时显示第1个界面,输入信息,点击“确定”,显示第2个界面,其中显示所输入的信息。点击返回,返回第1个界面。
要求:姓名、学号不能为空,如果为空,则在点击“确定”按钮时要有所提示。
代码:
TwoRegisterActivity.java
package top.yh.homework.two;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.List;
import top.yh.homework.R;
import top.yh.homework.util.StringUtil;
import top.yh.homework.util.ViewUtil;
public class TwoRegisterActivity extends AppCompatActivity {
List<String> hobbyList;
String major;
String hobby = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two_register);
final TwoRegisterActivity that = this;
hobbyList = new ArrayList<>();
String[] majorArray = getResources().getStringArray(R.array.majorArray);
major = majorArray[0];
EditText etName = findViewById(R.id.et_name);
EditText etSno = findViewById(R.id.et_sno);
Spinner spMajor = findViewById(R.id.sp_major);
RadioGroup rgSex = findViewById(R.id.eg_sex);
RadioButton rbMan = findViewById(R.id.rb_man);
RadioButton rbWoman = findViewById(R.id.rb_woman);
CheckBox cbBasketball = findViewById(R.id.cb_basketball);
CheckBox cbBaseball = findViewById(R.id.cb_baseball);
CheckBox cbBadminton = findViewById(R.id.cb_badminton);
CheckBox cbFootball = findViewById(R.id.cb_football);
RadioGroup rgPartyNumber = findViewById(R.id.rg_party_number);
cbBasketball.setOnCheckedChangeListener(new CheckBoxChangeListener(cbBasketball));
cbBaseball.setOnCheckedChangeListener(new CheckBoxChangeListener(cbBaseball));
cbBadminton.setOnCheckedChangeListener(new CheckBoxChangeListener(cbBadminton));
cbFootball.setOnCheckedChangeListener(new CheckBoxChangeListener(cbFootball));
spMajor.setSelection(0);
spMajor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
major = majorArray[i];
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Button btnConfirm = findViewById(R.id.btn_confirm);
btnConfirm.setOnClickListener(view -> {
String name = etName.getText().toString().trim();
String sno = etSno.getText().toString().trim();
if (StringUtil.isEmpty(sno) || StringUtil.isEmpty(name) || hobbyList.size() == 0) {
ViewUtil.showToast(that, "请将信息填写完整");
return;
}
String sex = rgSex.getCheckedRadioButtonId() == rbMan.getId() ? "男" : "女";
String isPartyNumber = rgPartyNumber.getCheckedRadioButtonId() == R.id.rb_yes ? "是" : "否";
hobbyList.forEach(ho -> hobby += ho + "/");
startActivity(new Intent(that, TwoResultActivity.class)
.putExtra("name", name)
.putExtra("sno", sno)
.putExtra("sex", sex)
.putExtra("isPartyNumber", isPartyNumber)
.putExtra("major", major)
.putExtra("hobby", hobby));
});
}
private class CheckBoxChangeListener implements CompoundButton.OnCheckedChangeListener {
CheckBox box;
public CheckBoxChangeListener(CheckBox box) {
this.box = box;
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String s = box.getText().toString();
if (b) {
hobbyList.add(s);
} else {
hobbyList.remove(s);
}
}
}
}
activity_two_register.xml
<?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:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
tools:context=".two.TwoRegisterActivity">
<TextView
android:layout_width="350dp"
android:layout_height="wrap_content"
android:background="@drawable/translucent_text_view"
android:gravity="center"
android:text="@string/two_register_title"
android:textSize="@dimen/tvTextSize" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="150dp"
android:layout_height="match_parent"
android:layout_marginEnd="10dp"
android:background="@drawable/translucent_text_view"
android:gravity="center"
android:text="@string/two_name"
android:textSize="@dimen/tvTextSize" />
<EditText
android:id="@+id/et_name"
android:layout_width="200dp"
android:layout_height="match_parent"
android:autofillHints=""
android:background="@drawable/edit_text_selector"
android:inputType="text"
tools:ignore="LabelFor" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="150dp"
android:layout_height="match_parent"
android:layout_marginEnd="10dp"
android:background="@drawable/translucent_text_view"
android:gravity="center"
android:text="@string/two_sno"
android:textSize="@dimen/tvTextSize" />
<EditText
android:id="@+id/et_sno"
android:layout_width="200dp"
android:layout_height="match_parent"
android:autofillHints=""
android:background="@drawable/edit_text_selector"
android:inputType="number"
tools:ignore="LabelFor" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="150dp"
android:layout_height="match_parent"
android:layout_marginEnd="10dp"
android:background="@drawable/translucent_text_view"
android:gravity="center"
android:text="@string/two_major"
android:textSize="@dimen/tvTextSize" />
<Spinner
android:id="@+id/sp_major"
android:layout_width="200dp"
android:layout_height="match_parent"
android:background="@drawable/edit_text_selector"
android:entries="@array/majorArray"
android:spinnerMode="dialog" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="150dp"
android:layout_height="match_parent"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:background="@drawable/translucent_text_view"
android:gravity="center"
android:text="@string/two_sex"
android:textSize="@dimen/tvTextSize" />
<RadioGroup
android:id="@+id/eg_sex"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_man"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginEnd="50dp"
android:checked="true"
android:text="@string/two_sex_man"
android:textSize="@dimen/tvTextSize" />
<RadioButton
android:id="@+id/rb_woman"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/two_sex_woman"
android:textSize="@dimen/tvTextSize" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:background="@drawable/translucent_text_view"
android:gravity="center"
android:text="@string/two_interests"
android:textSize="@dimen/tvTextSize" />
<CheckBox
android:id="@+id/cb_basketball"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/two_hobby_basketball"
android:textSize="@dimen/tvTextSize" />
<CheckBox
android:id="@+id/cb_football"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/two_hobby_football"
android:textSize="@dimen/tvTextSize" />
<CheckBox
android:id="@+id/cb_baseball"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/two_hobby_baseball"
android:textSize="@dimen/tvTextSize" />
<CheckBox
android:id="@+id/cb_badminton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/two_hobby_badminton"
android:textSize="@dimen/tvTextSize" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="150dp"
android:layout_height="match_parent"
android:background="@drawable/translucent_text_view"
android:gravity="center"
android:text="@string/two_is_party_member"
android:textSize="@dimen/tvTextSize" />
<RadioGroup
android:id="@+id/rg_party_number"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_yes"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginEnd="50dp"
android:checked="true"
android:text="@string/two_yes"
android:textSize="@dimen/tvTextSize" />
<RadioButton
android:id="@+id/rb_no"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/two_no"
android:textSize="@dimen/tvTextSize" />
</RadioGroup>
</LinearLayout>
<Button
android:id="@+id/btn_confirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/translucent_text_view"
android:text="@string/two_confirm"
android:textSize="@dimen/tvTextSize" />
</LinearLayout>
TwoResultActivity.java
package top.yh.homework.two;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import top.yh.homework.R;
import top.yh.homework.util.ViewUtil;
public class TwoResultActivity extends AppCompatActivity {
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_two_result);
findViewById(R.id.btn_back).setOnClickListener(view -> finish());
TextView tvName = findViewById(R.id.tv_name);
TextView tvSno = findViewById(R.id.tv_sno);
TextView tvHobby = findViewById(R.id.tv_hobby);
TextView tvMajor = findViewById(R.id.tv_major);
TextView tvSex = findViewById(R.id.tv_sex);
TextView tvPartyMember = findViewById(R.id.tv_party_member);
try {
tvName.setText(getString(R.string.two_name) + ":" + intent.getStringExtra("name"));
tvSno.setText(getString(R.string.two_sno) +":" +intent.getStringExtra("sno"));
tvHobby.setText(getString(R.string.two_interests) + ":" + intent.getStringExtra("hobby"));
tvMajor.setText(getString(R.string.two_major) + ":" + intent.getStringExtra("major"));
tvSex.setText(getString(R.string.two_sex) + ":" + intent.getStringExtra("sex"));
tvPartyMember.setText(getString(R.string.two_party_member) + ":" + intent.getStringExtra("isPartyNumber"));
}catch (Exception e){
e.printStackTrace();
ViewUtil.showToast(this,"数据传输失败");
}
}
}
activity_two_result.xml
<?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:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
tools:context=".two.TwoResultActivity">
<TextView
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:background="@drawable/translucent_text_view"
android:gravity="center"
android:text="@string/two_result_title"
android:textSize="@dimen/tvTextSize" />
<TextView
android:id="@+id/tv_name"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@drawable/translucent_text_view"
android:textSize="@dimen/tvTextSize" />
<TextView
android:id="@+id/tv_sno"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@drawable/translucent_text_view"
android:textSize="@dimen/tvTextSize" />
<TextView
android:id="@+id/tv_major"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@drawable/translucent_text_view"
android:textSize="@dimen/tvTextSize" />
<TextView
android:id="@+id/tv_sex"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@drawable/translucent_text_view"
android:textSize="@dimen/tvTextSize" />
<TextView
android:id="@+id/tv_hobby"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@drawable/translucent_text_view"
android:textSize="@dimen/tvTextSize" />
<TextView
android:id="@+id/tv_party_member"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@drawable/translucent_text_view"
android:textSize="@dimen/tvTextSize" />
<Button
android:id="@+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/translucent_text_view"
android:text="@string/two_back"
android:textSize="@dimen/tvTextSize" />
</LinearLayout>
3. 设计一个APP,使用listview显示20种水果的名称和对应图片,点击一个水果,显示该水果的介绍。
代码:
ThreeMainActivity.java
package top.yh.homework.three;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.List;
import java.util.Map;
import top.yh.homework.R;
import top.yh.homework.three.adapter.ThreeAdapter;
import top.yh.homework.three.entity.Fruit;
public class ThreeMainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_three_main);
ListView lvList = findViewById(R.id.lv_list);
List<Fruit> list = Fruit.getDefaultList();
final ThreeMainActivity that = this;
Map<String, String> descMap = Fruit.getDescMap();
ThreeAdapter adapter = new ThreeAdapter(this, list);
lvList.setAdapter(adapter);
lvList.setOnItemClickListener((adapterView, view, i, l) -> {
new AlertDialog.Builder(that).setTitle(list.get(i).name)
.setMessage(descMap.get(list.get(i).name))
.setPositiveButton("确定", (dialog, id) -> {
})
.setNegativeButton("取消", (dialog, id) -> {
}).create().show();
});
}
}
activity_three_main.xml
<?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="wrap_content"
android:orientation="vertical"
tools:context=".three.ThreeMainActivity">
<ListView
android:id="@+id/lv_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Fruit.java
package top.yh.homework.three.entity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import top.yh.homework.R;
/**
* @user
* @date
*/
public class Fruit {
public int img;
public String name;
public Fruit(int img, String name) {
this.img = img;
this.name = name;
}
private static final Integer[] iconArray = {
R.drawable.apple, R.drawable.banana, R.drawable.lemon,
R.drawable.mangosteen, R.drawable.watermelon
};
private final static String[] startArray = {
"苹果", "香蕉", "柠檬",
"山竹", "西瓜"
};
private final static String[] descArray = {
"苹果(Malus pumila Mill.),蔷薇科苹果属落叶乔木植物,茎干较高,小枝短而粗,呈圆柱形;叶片椭圆形,表面光滑,边缘有锯齿,叶柄粗壮;花朵较小呈伞状,淡粉色,表面有绒毛;果实较大,呈扁球形,果梗短粗;花期5月;果期7~10月。苹果名称最早是见于明代王世懋的《学圃余疏》“北土之苹婆果,即花红一种之变也。",
"香蕉(Musa nana Lour.),芭蕉科芭蕉属多年生草本植物,植株丛生,有匐匍茎;假茎浓绿有黑色斑点;叶片长圆形,上面为深绿色,无白粉,下面浅绿色;花朵为乳白色或淡紫色;果实呈弯曲的弓状,有棱,果皮为青绿色,成熟后变黄;果肉松软,黄白色,味甜香味浓,无种子",
"柠檬(Citrus × limon (Linnaeus) Osbeck),芸香科柑橘属木本植物,枝少刺或近于无刺,嫩叶及花芽暗紫红色;叶为卵形或椭圆形;花瓣外面为淡紫红色,内面白色;果实为椭圆形或卵形,果皮厚,柠檬黄色;花期4~5月;果期9~11月。",
"山竹(拉丁学名:Garcinia mangostana L.)是藤黄科藤黄属植物,原产于马鲁古,亚洲和非洲热带地区广泛栽培,喜欢有机物丰富、pH值在5~6.5的砂壤。",
"西瓜(Citrullus lanatus (Thunb.) Matsum. & Nakai),是葫芦科西瓜属一年生蔓生藤本植物,形态一般近似于球形或椭圆形,颜色有深绿、浅绿或带有黑绿条带或斑纹;瓜籽多为黑色,呈椭圆形,头尖;茎枝粗壮,有淡黄褐色的柔毛;叶片如纸,呈三角状卵形,边缘呈波状。花果期5—6月。 因9世纪自西域传入中国,故名西瓜。",
};
public static List<Fruit> getDefaultList() {
List<Fruit> list = new ArrayList<>();
for (int i = 0; i < iconArray.length; i++) {
list.add(new Fruit(iconArray[i], startArray[i]));
}
return list;
}
public static Map<String, String> getDescMap() {
Map<String, String> map = new HashMap<>(descArray.length);
for (int i = 0; i < descArray.length; i++) {
map.put(startArray[i], descArray[i]);
}
return map;
}
}
ThreeAdapter.java
package top.yh.homework.three.adapter;
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.TextView;
import java.util.List;
import top.yh.homework.R;
import top.yh.homework.three.entity.Fruit;
/**
* @user
* @date
*/
public class ThreeAdapter extends BaseAdapter {
private Context context;
private List<Fruit> list;
public ThreeAdapter(Context context, List<Fruit> list) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {
//获取列表项的个数
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if (view == null) {
//根据布局文件生成转换视图对象
view = LayoutInflater.from(context).inflate(R.layout.item_fruit, null);
viewHolder = new ViewHolder(view.findViewById(R.id.iv_icon),
view.findViewById(R.id.tv_name));
//将视图持有者保存到转换视图中
view.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
//给控件设置好数据
Fruit item = list.get(i);
viewHolder.ivIcon.setImageResource(item.img);
viewHolder.tvName.setText(item.name);
return view;
}
public static final class ViewHolder{
public ImageView ivIcon;
public TextView tvName;
public ViewHolder(ImageView ivIcon, TextView tvName) {
this.ivIcon = ivIcon;
this.tvName = tvName;
}
}
}
item_fruit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<ImageView
android:id="@+id/iv_icon"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:src="@drawable/banana"
android:scaleType="fitCenter"/>
<TextView
android:id="@+id/tv_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:gravity="center"
android:textSize="@dimen/tvTextSize"
android:textColor="@color/purple_700"
android:text="水果"/>
</LinearLayout>
4、在sd卡中存入一个文件,保存若干个整数,每个整数用空格分隔,当app运行时,从该文件中读取数据,并计算显示其和
<!--存储权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<application
...
android:requestLegacyExternalStorage="true"
android:usesCleartextTraffic="true"
...>
代码:
FourMainActivity.java
package top.yh.homework.four;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import top.yh.homework.R;
import top.yh.homework.util.FileUtil;
import top.yh.homework.util.ViewUtil;
public class FourMainActivity extends AppCompatActivity {
private String FILE_SAVE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MobileReport/";
private String FILE_NAME = "user.txt";
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private boolean havePermission = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_four_main);
checkPermission();
//写文件
String context = "1 2 3 4 5 6 7 8 9 10";
FileUtil.writeToSd(FILE_SAVE_PATH, FILE_NAME, context);
TextView tvRes = findViewById(R.id.tv_res);
findViewById(R.id.btn_display).setOnClickListener(view -> {
//读文件
String res = FileUtil.readToSd(FILE_SAVE_PATH, FILE_NAME);
String[] s = res.split(" ");
int sum = 0;
for (String s1 : s) {
sum += Integer.parseInt(s1);
}
tvRes.setText(String.valueOf(sum));
tvRes.setVisibility(View.VISIBLE);
});
}
@Override
protected void onResume() {
super.onResume();
checkPermission();
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_EXTERNAL_STORAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
havePermission = true;
ViewUtil.showToast(this, "授权成功!");
} else {
havePermission = false;
ViewUtil.showToast(this, "授权被拒绝!");
}
}
}
private AlertDialog dialog;
private void checkPermission() {
//检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
if (Build.VERSION.SDK_INT >= 30) {
if (!Environment.isExternalStorageManager()) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
dialog = new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage("请开启文件访问权限,否则无法正常使用本应用!")
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
})
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivity(intent);
}
}).create();
dialog.show();
} else {
havePermission = true;
Log.i("swyLog", "Android 11以上,当前已有权限");
}
} else {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//申请权限
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
dialog = new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage("请开启文件访问权限,否则无法正常使用本应用!")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
ActivityCompat.requestPermissions(FourMainActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
}).create();
dialog.show();
} else {
havePermission = true;
Log.i("swyLog", "Android 6.0以上,11以下,当前已有权限");
}
} else {
havePermission = true;
Log.i("swyLog", "Android 6.0以下,已获取权限");
}
}
}
}
activity_four_main.xml
<?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"
android:layout_gravity="center"
android:gravity="center"
tools:context=".four.FourMainActivity">
<Button
android:id="@+id/btn_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/four_display"
android:layout_marginBottom="20dp"
android:textSize="@dimen/tvTextSize"
android:background="@drawable/translucent_text_view"/>
<TextView
android:id="@+id/tv_res"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="@dimen/tvTextSize"
android:background="@drawable/translucent_text_view"
android:visibility="gone"/>
</LinearLayout>
FileUtil.java
public static String readToSd(String path, String name) {
InputStream inputStream = null;
Reader reader = null;
BufferedReader bufferedReader = null;
try {
File storage = new File(path);
if (!storage.exists()) {
return "";
}
File file = new File(storage, name);
if (!file.exists()) {
return "";
}
inputStream = Files.newInputStream(file.toPath());
reader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(reader);
StringBuilder result = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
result.append(temp);
}
String value = decodeToString(result.toString());
Log.i("swyLog", "upload 密文:" + result);
Log.i("swyLog", "upload 明文:" + value);
return value;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
/**
* 写入文件方法
*
* @param content
*/
public static void writeToSd(String path, String mode, String content) {
if (StringUtil.isEmpty(content)) {
return;
}
Log.i("swyLog", "saveLoginAccount called");
String value = encodeToString(content);
Log.i("swyLog", "save 明文:" + content);
Log.i("swyLog", "save 密文:" + value);
File storage = new File(path);
if (!storage.exists()) {
storage.mkdirs();
}
File tmepfile = new File(storage.getPath());
if (!tmepfile.exists()) {
tmepfile.mkdirs();
}
File file = new File(tmepfile, mode);
if (file.exists()) {
Log.i("swyLog", "删除原有文件");
file.delete();
}
if (!file.exists()) {
Log.i("swyLog", "文件删除成功");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(value.getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5、设计一个app,界面如下,有两个按钮,当点击打卡按钮,则在app中增加一个当前时间的打卡记录,点击显示记录按钮,显示所有的打卡记录
代码:
FiveMainActivity.java
package top.yh.homework.five;
import androidx.appcompat.app.AppCompatActivity;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import top.yh.homework.R;
import top.yh.homework.five.adapter.ListAdapter;
import top.yh.homework.five.entity.CardInfo;
import top.yh.homework.five.helper.SqliteHelper;
import top.yh.homework.util.TimeUtil;
import top.yh.homework.util.ViewUtil;
public class FiveMainActivity extends AppCompatActivity {
private SqliteHelper helper;
private List<CardInfo> list;
private ListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_five_main);
final FiveMainActivity that = this;
Button btnClock = findViewById(R.id.btn_clock_in);
Button btnDisPlay = findViewById(R.id.btn_display);
ListView lvList = findViewById(R.id.lv_list);
list = new ArrayList<>();
adapter = new ListAdapter(this, list);
lvList.setAdapter(adapter);
btnClock.setOnClickListener(view -> {
String time = TimeUtil.getTimeToYearMonthDayHourMinuteSecond();
if (helper.save(time) > 0L) {
ViewUtil.showToast(that,"打卡成功");
}
});
btnDisPlay.setOnClickListener(view -> {
list.clear();
list.addAll(helper.queryAll());
adapter.notifyDataSetChanged();
});
}
@Override
protected void onStart() {
super.onStart();
helper = SqliteHelper.getInstance(this);
helper.openReadLink();
helper.openWriteLink();
}
@Override
protected void onStop() {
super.onStop();
helper.closeLink();
}
}
activity_five_main.xml
<?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=".five.FiveMainActivity">
<LinearLayout
android:layout_gravity="center"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_clock_in"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/translucent_text_view"
android:text="@string/five_clock_in"
android:textSize="@dimen/tvTextSize" />
<Button
android:id="@+id/btn_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20sp"
android:background="@drawable/translucent_text_view"
android:text="@string/five_display_records"
android:textSize="@dimen/tvTextSize" />
</LinearLayout>
<ListView
android:id="@+id/lv_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
ListAdapter.java
package top.yh.homework.five.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import top.yh.homework.R;
import top.yh.homework.five.entity.CardInfo;
/**
* @user
* @date
*/
public class ListAdapter extends BaseAdapter {
private Context context;
private List<CardInfo> list;
public ListAdapter(Context context, List<CardInfo> list) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {
//获取列表项的个数
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if (view == null) {
//根据布局文件生成转换视图对象
view = LayoutInflater.from(context).inflate(R.layout.item_five_list, null);
viewHolder = new ViewHolder(view.findViewById(R.id.tv_time));
//将视图持有者保存到转换视图中
view.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
//给控件设置好数据
CardInfo item = list.get(i);
viewHolder.tvTime.setText(item.timer);
return view;
}
public static final class ViewHolder{
public TextView tvTime;
public ViewHolder( TextView tvTime) {
this.tvTime = tvTime;
}
}
}
item_five_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<TextView
android:id="@+id/tv_time"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:gravity="center"
android:textSize="@dimen/tvTextSize"
android:textColor="@color/purple_700"
android:text="水果"/>
</LinearLayout>
CardInfo.java
package top.yh.homework.five.entity;
/**
* @user
* @date
*/
public class CardInfo {
public int id;
public String timer;
public CardInfo() {
}
public CardInfo(int id, String timer) {
this.id = id;
this.timer = timer;
}
}
SqliteHelper.java
package top.yh.homework.five.helper;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import top.yh.homework.five.entity.CardInfo;
/**
* @user
* @date
*/
public class SqliteHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "card.db";
private static final String TABLE_NAME = "card_info";
private static final int DB_VERSION = 1;
private static SqliteHelper helper;
/**
* 读实例
*/
private SQLiteDatabase rsd = null;
/**
* 写实例
*/
private SQLiteDatabase wsd = null;
private SqliteHelper(@Nullable Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public static SqliteHelper getInstance(Context context) {
if (helper == null) {
helper = new SqliteHelper(context);
}
return helper;
}
/**
* 打开数据库的读连接
*
* @return
*/
public SQLiteDatabase openReadLink() {
if (rsd == null || !rsd.isOpen()) {
rsd = helper.getReadableDatabase();
}
return rsd;
}
/**
* 打开数据库的写连接
*
* @return
*/
public SQLiteDatabase openWriteLink() {
if (wsd == null || !wsd.isOpen()) {
wsd = helper.getWritableDatabase();
}
return wsd;
}
public void closeLink() {
if (rsd != null && rsd.isOpen()) {
rsd.close();
rsd = null;
}
if (wsd != null && wsd.isOpen()) {
wsd.close();
wsd = null;
}
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String sql = "create table if not exists " + TABLE_NAME +
"(_id integer primary key autoincrement not null," +
"timer text not null);";
sqLiteDatabase.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long save(String timer) {
ContentValues values = new ContentValues();
values.put("timer", timer);
return wsd.insert(TABLE_NAME, null, values);
}
@SuppressLint("Range")
public List<CardInfo> queryAll() {
List<CardInfo> list = new ArrayList<>();
Cursor cursor = rsd.rawQuery("select * from " + TABLE_NAME, null);
while (cursor.moveToNext()){
list.add(new CardInfo(
cursor.getInt(cursor.getColumnIndex("_id")),
cursor.getString(cursor.getColumnIndex("timer"))
));
}
cursor.close();
return list;
}
}
6. 设计一个APP,具有两个线程,一个线程计算1+2…+n的和,一个线程计算1*2*3*….n的乘积(n的值从键盘输入),并显示结果
代码:
SixMainActivity.java
package top.yh.homework.six;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import top.yh.homework.R;
import top.yh.homework.util.StringUtil;
import top.yh.homework.util.ViewUtil;
public class SixMainActivity extends AppCompatActivity {
private StringBuilder builder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_six_main);
final SixMainActivity that = this;
builder = new StringBuilder();
EditText etNum = findViewById(R.id.et_num);
Button btnCal = findViewById(R.id.btn_cal);
TextView tvRes = findViewById(R.id.tv_res);
btnCal.setOnClickListener(view -> {
String num = etNum.getText().toString().trim();
if (StringUtil.isEmpty(num)) {
ViewUtil.showToast(that,"请输入数字");
return;
}
int n = Integer.parseInt(num);
that.runOnUiThread(() -> {
builder.append("和为:").append(n * (n + 1) / 2);
tvRes.setText(builder);
tvRes.setVisibility(View.VISIBLE);
});
that.runOnUiThread(()-> {
int sum = 1;
for (int i = 1; i <= n; i++) {
sum *= i;
}
builder.append(" 乘积为:").append(sum);
tvRes.setText(builder);
tvRes.setVisibility(View.VISIBLE);
});
});
}
}
activity_six_main.xml
<?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:orientation="vertical"
android:layout_gravity="center"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".six.SixMainActivity">
<LinearLayout
android:layout_width="350dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="150dp"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginEnd="20dp"
android:text="@string/six_input_number"
android:textSize="@dimen/tvTextSize"
android:background="@drawable/translucent_text_view"/>
<EditText
android:id="@+id/et_num"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/edit_text_selector"
android:inputType="number"/>
</LinearLayout>
<Button
android:id="@+id/btn_cal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/one_cal"
android:textSize="@dimen/tvTextSize"
android:layout_marginTop="20dp"
android:background="@drawable/translucent_text_view"/>
<TextView
android:id="@+id/tv_res"
android:layout_width="250dp"
android:layout_marginTop="50dp"
android:layout_height="wrap_content"
android:textSize="@dimen/tvTextSize"
android:background="@drawable/translucent_text_view"
android:visibility="gone"/>
</LinearLayout>
7. 设计一个app,可以绘制矩形、圆、直线,其中绘制坐标可以输入
代码:
SevenMainActivity.java
package top.yh.homework.seven;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import top.yh.homework.R;
import top.yh.homework.util.StringUtil;
import top.yh.homework.util.ViewUtil;
public class SevenMainActivity extends AppCompatActivity {
private EditText etX;
private EditText etY;
private int x;
private int y;
private final int LINE = 50;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seven_main);
Button btnLine = findViewById(R.id.btn_line);
Button btnRectangle = findViewById(R.id.btn_rectangle);
Button btnCircle = findViewById(R.id.btn_circle);
ImageView ivIcon = findViewById(R.id.iv_icon);
etX = findViewById(R.id.et_x);
etY = findViewById(R.id.et_y);
// 创建空白的bitmap
Bitmap bitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);
// 新建画布,关联bitmap
Canvas canvas = new Canvas(bitmap);
// 绘制背景
canvas.drawColor(Color.WHITE);
//创建蓝画笔
Paint bluePaint = new Paint();
bluePaint.setStyle(Paint.Style.STROKE);
bluePaint.setColor(Color.BLUE);
//画笔粗细为9像素点
bluePaint.setStrokeWidth(9);
btnLine.setOnClickListener(view -> {
if (check()) {
canvas.drawColor(0,PorterDuff.Mode.CLEAR);
//划线
canvas.drawLine(x, y, x + LINE, y, bluePaint);
//显示bitmap到ImageView中
ivIcon.setImageBitmap(bitmap);
}
});
btnCircle.setOnClickListener(view -> {
if (check()) {
canvas.drawColor(0,PorterDuff.Mode.CLEAR);
canvas.drawCircle(x,y,LINE,bluePaint);
ivIcon.setImageBitmap(bitmap);
}
});
btnRectangle.setOnClickListener(view -> {
if (check()) {
canvas.drawColor(0,PorterDuff.Mode.CLEAR);
Rect rect = new Rect();
rect.top = y;
rect.bottom = y + LINE;
rect.left = x;
rect.right = x + LINE;
canvas.drawRect(rect, bluePaint);
ivIcon.setImageBitmap(bitmap);
}
});
}
private boolean check(){
String x = etX.getText().toString().trim();
String y = etY.getText().toString().trim();
if (StringUtil.isEmpty(x) || StringUtil.isEmpty(y)) {
ViewUtil.showToast(this,"请输入坐标");
return false;
}
this.x = Integer.parseInt(x);
this.y = Integer.parseInt(y);
return true;
}
}
activity_seven_main.xml
<?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=".seven.SevenMainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/btn_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/translucent_text_view"
android:text="@string/seven_draw_a_circle"
android:textSize="@dimen/tvTextSize" />
<Button
android:id="@+id/btn_line"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/translucent_text_view"
android:text="@string/seven_draw_a_straight_line"
android:textSize="@dimen/tvTextSize" />
<Button
android:id="@+id/btn_rectangle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/translucent_text_view"
android:text="@string/seven_draw_rectangle"
android:textSize="@dimen/tvTextSize" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:text="@string/seven_please_enter_coordinates"
android:textSize="@dimen/tvTextSize" />
<EditText
android:id="@+id/et_x"
android:layout_width="70dp"
android:layout_height="match_parent"
android:background="@drawable/edit_text_selector"
android:gravity="center"
android:hint="@string/seven_x"
android:inputType="number"
android:textSize="@dimen/tvTextSize" />
<EditText
android:id="@+id/et_y"
android:layout_width="70dp"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:background="@drawable/edit_text_selector"
android:gravity="center"
android:hint="@string/seven_y"
android:inputType="number"
android:textSize="@dimen/tvTextSize" />
</LinearLayout>
<ImageView
android:id="@+id/iv_icon"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
通用文件
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- 存储权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:requestLegacyExternalStorage="true"
android:supportsRtl="true"
android:theme="@style/Theme.HomeWork"
android:usesCleartextTraffic="true"
tools:targetApi="31">
<activity
android:name=".seven.SevenMainActivity"
android:exported="false" />
<activity
android:name=".six.SixMainActivity"
android:exported="false" />
<activity
android:name=".five.FiveMainActivity"
android:exported="false" />
<activity
android:name=".four.FourMainActivity"
android:exported="true" />
<activity
android:name=".three.ThreeMainActivity"
android:exported="false" />
<activity
android:name=".two.TwoResultActivity"
android:exported="false" />
<activity
android:name=".two.TwoRegisterActivity"
android:exported="false" />
<activity
android:name=".one.ResultActivity"
android:exported="false" />
<activity
android:name=".one.OneActivity"
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>
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="transparent">#00000000</color>
</resources>
spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="majorArray">
<item>计算机</item>
<item>软件</item>
<item>财务</item>
<item>电信</item>
<item>电气</item>
</string-array>
</resources>
strings.xml
<resources>
<string name="app_name">HomeWork</string>
<string name="one">第一个作业</string>
<string name="one_one_number">第一个数</string>
<string name="one_two_number">第一个数</string>
<string name="one_result">结果</string>
<string name="one_cal">计算</string>
<string name="one_back">返回</string>
<string name="two">第二个作业</string>
<string name="two_register_title">注册信息</string>
<string name="two_name">姓名</string>
<string name="two_sno">学号</string>
<string name="two_major">专业</string>
<string name="two_sex">性别</string>
<string name="two_sex_man">男</string>
<string name="two_sex_woman">女</string>
<string name="two_interests">爱好</string>
<string name="two_party_member">党员</string>
<string name="two_is_party_member">是否党员</string>
<string name="two_yes">是</string>
<string name="two_no">否</string>
<string name="two_confirm">确定</string>
<string name="two_back">返回</string>
<string name="two_hobby_basketball">篮球</string>
<string name="two_hobby_football">足球</string>
<string name="two_hobby_baseball">棒球</string>
<string name="two_hobby_badminton">羽毛球</string>
<string name="two_result_title">你提交的信息</string>
<string name="three">第三个作业</string>
<string name="four">第四个作业</string>
<string name="four_display">显示其和</string>
<string name="five">第五个作业</string>
<string name="five_clock_in">打卡</string>
<string name="five_display_records">显示记录</string>
<string name="six">第六个作业</string>
<string name="six_input_number">请输入整数</string>
<string name="seven">第七个作业</string>
<string name="seven_draw_rectangle">绘制矩形</string>
<string name="seven_draw_a_circle">绘制圆形</string>
<string name="seven_draw_a_straight_line">绘制直线</string>
<string name="seven_please_enter_coordinates">输入坐标</string>
<string name="seven_x">x</string>
<string name="seven_y">y</string>
</resources>
translucent_text_view.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/transparent" />
<stroke android:width="3dip" android:color="@color/black" />
<corners android:radius="10dp"/>
<padding android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp"/>
</shape>
shape_edit_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--指定形状内部的填充颜色-->
<solid android:color="#ffffff"/>
<!-- 指定形状轮廓的粗细与颜色-->
<stroke android:width="1dp" android:color="#aaaaaa"/>
<!-- 指定形状四个圆角的半径-->
<corners android:radius="5dp"/>
<!-- 指定形状四个方向的间距-->
<padding android:bottom="2dp" android:left="2dp" android:right="2dp" android:top="2dp"/>
</shape>
shape_edit_focus.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--指定形状内部的填充颜色-->
<solid android:color="#ffffff"/>
<!-- 指定形状轮廓的粗细与颜色-->
<stroke android:width="1dp" android:color="#0000ff"/>
<!-- 指定形状四个圆角的半径-->
<corners android:radius="5dp"/>
<!-- 指定形状四个方向的间距-->
<padding android:bottom="2dp" android:left="2dp" android:right="2dp" android:top="2dp"/>
</shape>
edit_text_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_edit_focus" android:state_focused="true" />
<item android:drawable="@drawable/shape_edit_normal"/>
</selector>