This commit is contained in:
icewithcola 2024-05-24 12:48:34 +08:00
parent a1cccd9890
commit daeaee0d3e
24 changed files with 488 additions and 379 deletions

View file

@ -22,7 +22,20 @@
<State /> <State />
</entry> </entry>
<entry key="app"> <entry key="app">
<State /> <State>
<runningDeviceTargetSelectedWithDropDown>
<Target>
<type value="RUNNING_DEVICE_TARGET" />
<deviceKey>
<Key>
<type value="VIRTUAL_DEVICE_PATH" />
<value value="$USER_HOME$/.android/avd/Resizable_Experimental_API_34.avd" />
</Key>
</deviceKey>
</Target>
</runningDeviceTargetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2024-05-24T03:51:09.939185298Z" />
</State>
</entry> </entry>
</value> </value>
</component> </component>

View file

@ -11,8 +11,8 @@ android {
applicationId = "uk.kagurach.android101" applicationId = "uk.kagurach.android101"
minSdk = 31 minSdk = 31
targetSdk = 34 targetSdk = 34
versionCode = 151 versionCode = 153
versionName = "1.5.1" versionName = "1.5.3"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
} }

View file

@ -1,9 +1,10 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android">
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.VIBRATE" />
<application <application
android:allowBackup="true" android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules" android:dataExtractionRules="@xml/data_extraction_rules"
@ -12,8 +13,18 @@
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.Android101" android:theme="@style/Theme.Android101">
tools:targetApi="31">
<receiver
android:name=".vibrationBroadcastReceiver.vibrationBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.VIBRATE">
<intent-filter>
<action android:name="uk.kagurach.android101.vibrationBroadcastReceiver"/>
</intent-filter>
</receiver>
<activity <activity
android:name=".Page4OtherActivity" android:name=".Page4OtherActivity"
android:exported="false" /> android:exported="false" />

View file

@ -3,84 +3,82 @@ package uk.kagurach.android101
import android.content.Context import android.content.Context
import kotlin.math.pow import kotlin.math.pow
fun Kaculate(src: String,ctx :Context) : String{ fun Kaculate(src: String, ctx: Context): String {
if (src.isBlank()){ if (src.isBlank()) {
return src return src
} }
val OpList = charArrayOf('+','-','x','/','^') val OpList = charArrayOf('+', '-', 'x', '/', '^')
var numStack = floatArrayOf() var numStack = floatArrayOf()
var opStack = charArrayOf() var opStack = charArrayOf()
var _curnum = "" var _curnum = ""
for (i in src.indices){ for (i in src.indices) {
if (src[i] in '0'..'9' || src[i] == '.'){ if (src[i] in '0'..'9' || src[i] == '.') {
_curnum += src[i] _curnum += src[i]
} } else if (src[i] in OpList) {
else if (src[i] in OpList){
try { try {
numStack += _curnum.toFloat() numStack += _curnum.toFloat()
_curnum = "" _curnum = ""
}catch (e:Exception){ } catch (e: Exception) {
ToastHelper.ShowToast(e.toString(),ctx) ToastHelper.ShowToast(e.toString(), ctx)
return src return src
} }
opStack += src[i] opStack += src[i]
} } else {
else{ ToastHelper.ShowToast("Unknown input char:" + src[i].toString(), ctx)
ToastHelper.ShowToast("Unknown input char:" + src[i].toString(),ctx)
return src return src
} }
} }
if (_curnum.isNotEmpty()){ if (_curnum.isNotEmpty()) {
try { try {
numStack += _curnum.toFloat() numStack += _curnum.toFloat()
}catch (e:Exception){ } catch (e: Exception) {
ToastHelper.ShowToast(e.toString(),ctx) ToastHelper.ShowToast(e.toString(), ctx)
return src return src
} }
} }
if (numStack.size != opStack.size+1 ){ if (numStack.size != opStack.size + 1) {
ToastHelper.ShowToast("Ops and nums Not Match!",ctx) ToastHelper.ShowToast("Ops and nums Not Match!", ctx)
return src return src
} }
// ^ // ^
if ('^' in opStack){ if ('^' in opStack) {
var intStackCurr = 0 var intStackCurr = 0
for (i in opStack.indices){ for (i in opStack.indices) {
if (opStack[i]!='^'){ if (opStack[i] != '^') {
intStackCurr ++ intStackCurr++
continue continue
} }
val a = numStack[intStackCurr] val a = numStack[intStackCurr]
val b = numStack[intStackCurr+1] val b = numStack[intStackCurr + 1]
numStack[intStackCurr] = a.pow(b) numStack[intStackCurr] = a.pow(b)
numStack = dropAtIdx(numStack,intStackCurr+1) numStack = dropAtIdx(numStack, intStackCurr + 1)
} }
} }
// x and / // x and /
var intStackCurr = 0 var intStackCurr = 0
for (i in opStack.indices){ for (i in opStack.indices) {
if (opStack[i]!='x'&&opStack[i]!='/'){ if (opStack[i] != 'x' && opStack[i] != '/') {
intStackCurr ++ intStackCurr++
continue continue
} }
val a = numStack[intStackCurr] val a = numStack[intStackCurr]
val b = numStack[intStackCurr+1] val b = numStack[intStackCurr + 1]
if (opStack[i] == 'x'){ if (opStack[i] == 'x') {
numStack[intStackCurr] = a*b numStack[intStackCurr] = a * b
}else{ } else {
numStack[intStackCurr] = a/b numStack[intStackCurr] = a / b
} }
numStack = dropAtIdx(numStack,intStackCurr+1) numStack = dropAtIdx(numStack, intStackCurr + 1)
} }
// + and - // + and -
@ -88,10 +86,10 @@ fun Kaculate(src: String,ctx :Context) : String{
for (i in opStack) { for (i in opStack) {
if (i == '+') { if (i == '+') {
numStack[0] += numStack[1] numStack[0] += numStack[1]
numStack = dropAtIdx(numStack,1) numStack = dropAtIdx(numStack, 1)
} else if (i=='-') { } else if (i == '-') {
numStack[0] -= numStack[1] numStack[0] -= numStack[1]
numStack = dropAtIdx(numStack,1) numStack = dropAtIdx(numStack, 1)
} }
} }
} }
@ -99,14 +97,14 @@ fun Kaculate(src: String,ctx :Context) : String{
return numStack[0].toString() return numStack[0].toString()
} }
private fun dropAtIdx(array: FloatArray, idx:Int): FloatArray{ private fun dropAtIdx(array: FloatArray, idx: Int): FloatArray {
if (idx>array.size){ if (idx > array.size) {
throw IndexOutOfBoundsException() throw IndexOutOfBoundsException()
} }
var newArray = floatArrayOf() var newArray = floatArrayOf()
for (i in array.indices){ for (i in array.indices) {
if (i!=idx){ if (i != idx) {
newArray += array[i] newArray += array[i]
} }
} }

View file

@ -27,6 +27,7 @@ import java.util.Arrays;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
PageHelper pageHelper; PageHelper pageHelper;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
@ -41,30 +42,30 @@ public class MainActivity extends AppCompatActivity {
} }
@Override @Override
protected void onResume(){ protected void onResume() {
super.onResume(); super.onResume();
TextView tv = findViewById(R.id.tv_hello); TextView tv = findViewById(R.id.tv_hello);
textViewAppendString(tv,"Starting Initialize"); textViewAppendString(tv, "Starting Initialize");
if (Build.VERSION.SDK_INT >= 33) { if (Build.VERSION.SDK_INT >= 33) {
textViewAppendString(tv,"Find api > 33, checking permission"); textViewAppendString(tv, "Find api > 33, checking permission");
if (ContextCompat if (ContextCompat
.checkSelfPermission .checkSelfPermission
(MainActivity.this, Manifest.permission.POST_NOTIFICATIONS) (MainActivity.this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) { != PackageManager.PERMISSION_GRANTED) {
textViewAppendString(tv,"Acquiring POST_NOTIFICATIONS"); textViewAppendString(tv, "Acquiring POST_NOTIFICATIONS");
ActivityCompat.requestPermissions ActivityCompat.requestPermissions
(MainActivity.this, (MainActivity.this,
new String[]{Manifest.permission.POST_NOTIFICATIONS}, new String[]{Manifest.permission.POST_NOTIFICATIONS},
101); 101);
} }
textViewAppendString(tv,"Check Finished"); textViewAppendString(tv, "Check Finished");
textViewAppendString(tv,"提示:常桉有惊喜"); textViewAppendString(tv, "提示:常桉有惊喜");
} }
textViewAppendString(tv,"*************************\nfinished"); textViewAppendString(tv, "*************************\nfinished");
// Initialize Page Helper // Initialize Page Helper
pageHelper = new PageHelper(this,null,MainActivity2.class,this); pageHelper = new PageHelper(this, null, MainActivity2.class, this);
Button button = findViewById(R.id.Page1NextPage); Button button = findViewById(R.id.Page1NextPage);
button.setEnabled(true); button.setEnabled(true);
@ -72,28 +73,15 @@ public class MainActivity extends AppCompatActivity {
button.setOnLongClickListener(new LongClickHandler(this)); button.setOnLongClickListener(new LongClickHandler(this));
} }
private void textViewAppendString(@NonNull TextView tv, String s){ private void textViewAppendString(@NonNull TextView tv, String s) {
String last = tv.getText().toString(); String last = tv.getText().toString();
if (!last.endsWith("\n")){ if (!last.endsWith("\n")) {
last += "\n"; last += "\n";
} }
last += s; last += s;
tv.setText(last); tv.setText(last);
} }
private final class LongClickHandler implements View.OnLongClickListener
{
LongClickHandler(Context ctx){
context = ctx;
}
Context context;
@Override
public boolean onLongClick(View v){
CreateShortcut(context);
return false;
}
}
private void CreateShortcut(Context context) { private void CreateShortcut(Context context) {
ShortcutManager shortcutManager = ShortcutManager shortcutManager =
this.getSystemService(ShortcutManager.class); this.getSystemService(ShortcutManager.class);
@ -102,7 +90,7 @@ public class MainActivity extends AppCompatActivity {
try { try {
pinShortcutInfo = pinShortcutInfo =
new ShortcutInfo.Builder(context, "start_TODO").build(); new ShortcutInfo.Builder(context, "start_TODO").build();
}catch (Exception e){ } catch (Exception e) {
Log.e("ShortCutManager", Arrays.toString(e.getStackTrace())); Log.e("ShortCutManager", Arrays.toString(e.getStackTrace()));
return; return;
} }
@ -117,4 +105,18 @@ public class MainActivity extends AppCompatActivity {
successCallback.getIntentSender()); successCallback.getIntentSender());
} }
} }
private final class LongClickHandler implements View.OnLongClickListener {
Context context;
LongClickHandler(Context ctx) {
context = ctx;
}
@Override
public boolean onLongClick(View v) {
CreateShortcut(context);
return false;
}
}
} }

View file

@ -23,6 +23,7 @@ public class MainActivity2 extends AppCompatActivity {
PageHelper pageHelper; PageHelper pageHelper;
int _text_size = 70; int _text_size = 70;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
@ -33,11 +34,11 @@ public class MainActivity2 extends AppCompatActivity {
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets; return insets;
}); });
pageHelper = new PageHelper(this,MainActivity.class,Page3.class); pageHelper = new PageHelper(this, MainActivity.class, Page3.class);
} }
@Override @Override
protected void onResume(){ protected void onResume() {
super.onResume(); super.onResume();
Button button = findViewById(R.id.next_page_nav_2); Button button = findViewById(R.id.next_page_nav_2);
button.setOnClickListener(pageHelper.pageButtonHandler); button.setOnClickListener(pageHelper.pageButtonHandler);
@ -47,17 +48,17 @@ public class MainActivity2 extends AppCompatActivity {
public void set70sp(View view) { public void set70sp(View view) {
TextView t = findViewById(R.id.test2strview); TextView t = findViewById(R.id.test2strview);
t.setTextSize(TypedValue.COMPLEX_UNIT_SP,_text_size); t.setTextSize(TypedValue.COMPLEX_UNIT_SP, _text_size);
} }
public void set70dp(View view) { public void set70dp(View view) {
TextView t = findViewById(R.id.test2strview); TextView t = findViewById(R.id.test2strview);
t.setTextSize(TypedValue.COMPLEX_UNIT_DIP,_text_size); t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, _text_size);
} }
public void set70px(View view) { public void set70px(View view) {
TextView t = findViewById(R.id.test2strview); TextView t = findViewById(R.id.test2strview);
t.setTextSize(TypedValue.COMPLEX_UNIT_PX,_text_size); t.setTextSize(TypedValue.COMPLEX_UNIT_PX, _text_size);
} }
public void setColor(View view) { public void setColor(View view) {
@ -66,11 +67,11 @@ public class MainActivity2 extends AppCompatActivity {
EditText g_edit = findViewById(R.id.G); EditText g_edit = findViewById(R.id.G);
EditText b_edit = findViewById(R.id.B); EditText b_edit = findViewById(R.id.B);
int _r,_g,_b; int _r, _g, _b;
// Here we are testing toast // Here we are testing toast
if( r_edit.getText().toString().isEmpty() || if (r_edit.getText().toString().isEmpty() ||
g_edit.getText().toString().isEmpty()|| g_edit.getText().toString().isEmpty() ||
b_edit.getText().toString().isEmpty() ){ b_edit.getText().toString().isEmpty()) {
ToastHelper.SmartToast.ShowToast(""" ToastHelper.SmartToast.ShowToast("""
Please input R,G,B within 0-255 Please input R,G,B within 0-255
请在大小选择下方输入0-255的RGB""", 请在大小选择下方输入0-255的RGB""",
@ -81,26 +82,27 @@ public class MainActivity2 extends AppCompatActivity {
_r = Integer.parseInt(r_edit.getText().toString()); _r = Integer.parseInt(r_edit.getText().toString());
_g = Integer.parseInt(g_edit.getText().toString()); _g = Integer.parseInt(g_edit.getText().toString());
_b = Integer.parseInt(b_edit.getText().toString()); _b = Integer.parseInt(b_edit.getText().toString());
} catch (NumberFormatException e){ } catch (NumberFormatException e) {
ToastHelper.SmartToast.ShowToast(e.toString(),this); ToastHelper.SmartToast.ShowToast(e.toString(), this);
return; return;
} }
if (_r>=0&&_g>=0&&_b>=0&&_r<=255&&_g<=255&&_b<=255){ if (_r >= 0 && _g >= 0 && _b >= 0 && _r <= 255 && _g <= 255 && _b <= 255) {
t.setTextColor(Color.rgb(_r,_g,_b)); t.setTextColor(Color.rgb(_r, _g, _b));
}else{ } else {
ToastHelper.SmartToast.ShowToast( ToastHelper.SmartToast.ShowToast(
"The color: R="+_r+" G="+_g+" B="+_b+" is invalid!",this); "The color: R=" + _r + " G=" + _g + " B=" + _b + " is invalid!", this);
} }
} }
public void setText(View view) { public void setText(View view) {
TextView textView = findViewById(R.id.test2strview); TextView textView = findViewById(R.id.test2strview);
EditText editText = findViewById(R.id.Page2SetTestText); EditText editText = findViewById(R.id.Page2SetTestText);
String s; String s;
try { try {
s = editText.getText().toString(); s = editText.getText().toString();
}catch (Exception e){ } catch (Exception e) {
ToastHelper.SmartToast.ShowToast(e.toString(),this); ToastHelper.SmartToast.ShowToast(e.toString(), this);
return; return;
} }
textView.setText(s); textView.setText(s);
@ -116,14 +118,14 @@ public class MainActivity2 extends AppCompatActivity {
int size; int size;
try { try {
size = Integer.parseInt(ed.getText().toString()); size = Integer.parseInt(ed.getText().toString());
}catch (Exception e){ } catch (Exception e) {
ToastHelper.SmartToast.ShowToast(e.toString(),this); ToastHelper.SmartToast.ShowToast(e.toString(), this);
return; return;
} }
_text_size = size; _text_size = size;
sp.setText(size +"SP"); sp.setText(size + "SP");
dp.setText(size +"DP"); dp.setText(size + "DP");
px.setText(size +"PX"); px.setText(size + "PX");
} }

View file

@ -9,28 +9,30 @@ import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat.getSystemService import androidx.core.content.ContextCompat.getSystemService
import kotlin.random.Random
class NotificationHelper(_ctx: Context) { class NotificationHelper(_ctx: Context) {
val CHANNEL_ID = "DBG_PUSHER" val CHANNEL_ID = "DBG_PUSHER"
val name = "Debug Pusher" val name = "Debug Pusher"
var ctx: Context = _ctx var ctx: Context = _ctx
companion object { // Make notify id always increase companion object { // Make notify id always increase
var notifyID = 1 var notifyID = 1
} }
private val notificationManager = private val notificationManager =
getSystemService(ctx,NotificationManager::class.java) as NotificationManager getSystemService(ctx, NotificationManager::class.java) as NotificationManager
fun pushNotification(title:String,content:String) { fun pushNotification(title: String, content: String) {
val builder = NotificationCompat.Builder(ctx, CHANNEL_ID) val builder = NotificationCompat.Builder(ctx, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground) .setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title) .setContentTitle(title)
.setContentText(content) .setContentText(content)
.setPriority(NotificationCompat.PRIORITY_DEFAULT) .setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true) .setAutoCancel(true)
.setStyle(NotificationCompat.BigTextStyle() .setStyle(
.bigText(content)) NotificationCompat.BigTextStyle()
.bigText(content)
)
with(NotificationManagerCompat.from(ctx)) { with(NotificationManagerCompat.from(ctx)) {
if (ActivityCompat.checkSelfPermission( if (ActivityCompat.checkSelfPermission(
@ -55,7 +57,7 @@ class NotificationHelper(_ctx: Context) {
notificationManager.createNotificationChannel(channel) notificationManager.createNotificationChannel(channel)
} }
protected fun deleteNotificationChannel(){ protected fun deleteNotificationChannel() {
notificationManager.deleteNotificationChannel(CHANNEL_ID) notificationManager.deleteNotificationChannel(CHANNEL_ID)
} }
} }

View file

@ -14,11 +14,10 @@ import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat; import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat; import androidx.core.view.WindowInsetsCompat;
import java.util.List;
public class Page3 extends AppCompatActivity { public class Page3 extends AppCompatActivity {
PageHelper pageHelper; PageHelper pageHelper;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
@ -30,7 +29,7 @@ public class Page3 extends AppCompatActivity {
return insets; return insets;
}); });
pageHelper = new PageHelper(this,MainActivity2.class,Page4.class); pageHelper = new PageHelper(this, MainActivity2.class, Page4.class);
findViewById(R.id.P3_0).setOnClickListener(new CalculateOnClickListener()); findViewById(R.id.P3_0).setOnClickListener(new CalculateOnClickListener());
findViewById(R.id.P3_1).setOnClickListener(new CalculateOnClickListener()); findViewById(R.id.P3_1).setOnClickListener(new CalculateOnClickListener());
@ -59,62 +58,7 @@ public class Page3 extends AppCompatActivity {
findViewById(R.id.P3Nextpage).setOnLongClickListener(pageHelper.longClickHandler); findViewById(R.id.P3Nextpage).setOnLongClickListener(pageHelper.longClickHandler);
} }
private void setOpButton(boolean state) {
class CalculateOnClickListener implements View.OnClickListener{
@Override
public void onClick(View v){
TextView tv = findViewById(R.id.P3CalcResult);
String s = tv.getText().toString();
String o = ((Button)v).getText().toString();
Button dot = findViewById(R.id.P3Dot);
switch (o){
case "退格":
if (!s.isEmpty()){
if (s.length()==1){
s = "";
dot.setEnabled(true);
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(true);
}else {
s = s.substring(0, s.length() - 1);
dot.setEnabled(!isNumberWithDot(s));
setOpButton(s.substring(s.length()-1).matches("\\d|\\."));
}
}
break;
case "CE":
s = "";
dot.setEnabled(true);
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(true);
break;
case "=":
calc();
s = tv.getText().toString();
dot.setEnabled(!s.contains("."));
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(
!s.toLowerCase().contains("n")); // For Inf & NaN
return;
case ".":
dot.setEnabled(false);
s+='.';
break;
default:
s += o;
if (o.matches("\\d")) { // If inputted a number
setOpButton(true);
}else{ // Else an operator
dot.setEnabled(true);
setOpButton(false);
}
}
tv.setText(s);
}
}
private void setOpButton(boolean state){
findViewById(R.id.P3X).setEnabled(state); findViewById(R.id.P3X).setEnabled(state);
findViewById(R.id.P3Plus).setEnabled(state); findViewById(R.id.P3Plus).setEnabled(state);
findViewById(R.id.P3Minus).setEnabled(state); findViewById(R.id.P3Minus).setEnabled(state);
@ -122,25 +66,25 @@ public class Page3 extends AppCompatActivity {
findViewById(R.id.P3ChengFang).setEnabled(state); findViewById(R.id.P3ChengFang).setEnabled(state);
} }
private boolean isNumberWithDot(@NonNull String s){ private boolean isNumberWithDot(@NonNull String s) {
if (!s.contains(".")){ if (!s.contains(".")) {
return false; return false;
} }
boolean hasDot = false; boolean hasDot = false;
for (int i = s.length()-1; i >= 0; i--) { for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i); char c = s.charAt(i);
if (c=='+'||c=='-'||c=='x'||c=='/'||c=='^'){ if (c == '+' || c == '-' || c == 'x' || c == '/' || c == '^') {
return hasDot; return hasDot;
}else if (c=='.'){ } else if (c == '.') {
hasDot = true; hasDot = true;
} }
} }
return hasDot; return hasDot;
} }
private void calc(){ private void calc() {
TextView textView = findViewById(R.id.P3CalcResult); TextView textView = findViewById(R.id.P3CalcResult);
String result = Kaculate(textView.getText().toString(),this); String result = Kaculate(textView.getText().toString(), this);
if (result.contains(".")) { // In case of Infinity or NaN as a result if (result.contains(".")) { // In case of Infinity or NaN as a result
int i = 0; int i = 0;
@ -162,4 +106,57 @@ public class Page3 extends AppCompatActivity {
textView.setText(result); textView.setText(result);
} }
class CalculateOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
TextView tv = findViewById(R.id.P3CalcResult);
String s = tv.getText().toString();
String o = ((Button) v).getText().toString();
Button dot = findViewById(R.id.P3Dot);
switch (o) {
case "退格":
if (!s.isEmpty()) {
if (s.length() == 1) {
s = "";
dot.setEnabled(true);
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(true);
} else {
s = s.substring(0, s.length() - 1);
dot.setEnabled(!isNumberWithDot(s));
setOpButton(s.substring(s.length() - 1).matches("\\d|\\."));
}
}
break;
case "CE":
s = "";
dot.setEnabled(true);
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(true);
break;
case "=":
calc();
s = tv.getText().toString();
dot.setEnabled(!s.contains("."));
setOpButton(true);
findViewById(R.id.P3EqualButton).setEnabled(
!s.toLowerCase().contains("n")); // For Inf & NaN
return;
case ".":
dot.setEnabled(false);
s += '.';
break;
default:
s += o;
if (o.matches("\\d")) { // If inputted a number
setOpButton(true);
} else { // Else an operator
dot.setEnabled(true);
setOpButton(false);
}
}
tv.setText(s);
}
}
} }

View file

@ -1,6 +1,6 @@
package uk.kagurach.android101; package uk.kagurach.android101;
import android.app.Activity; import android.content.ComponentName;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
@ -14,16 +14,19 @@ import android.widget.TextView;
import androidx.activity.EdgeToEdge; import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts; import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets; import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat; import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat; import androidx.core.view.WindowInsetsCompat;
import uk.kagurach.android101.vibrationBroadcastReceiver.vibrationBroadcastReceiver;
public class Page4 extends AppCompatActivity { public class Page4 extends AppCompatActivity {
PageHelper pageHelper; PageHelper pageHelper;
ActivityResultLauncher mLauncher; ActivityResultLauncher mLauncher;
long startTime = 0;
long endTime = 0;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@ -35,49 +38,47 @@ public class Page4 extends AppCompatActivity {
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets; return insets;
}); });
pageHelper = new PageHelper(this, Page3.class,Page5.class); pageHelper = new PageHelper(this, Page3.class, Page5.class);
Button askAI = findViewById(R.id.P4AskAI); Button askAI = findViewById(R.id.P4AskAI);
askAI.setOnClickListener(new ButtonHandler()); askAI.setOnClickListener(new ButtonHandler());
Button nextPage = findViewById(R.id.P4PageButton); Button nextPage = findViewById(R.id.P4PageButton);
nextPage.setOnClickListener(pageHelper.pageButtonHandler); nextPage.setOnClickListener(pageHelper.pageButtonHandler);
nextPage.setOnLongClickListener(pageHelper.longClickHandler); nextPage.setOnLongClickListener(pageHelper.longClickHandler);
mLauncher = registerForActivityResult( Button vibrate = findViewById(R.id.P4Vibrate);
new ActivityResultContracts.StartActivityForResult(), vibrate.setOnClickListener(new VibrateButtonHandler());
result -> {
if (result!=null && result.getResultCode() == RESULT_OK ){ mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
assert result.getData() != null; if (result != null && result.getResultCode() == RESULT_OK) {
Bundle bundle = result.getData().getExtras(); assert result.getData() != null;
if (bundle!=null) { Bundle bundle = result.getData().getExtras();
String response = bundle.getString("reply"); if (bundle != null) {
TextView tv = findViewById(R.id.P4Result); String response = bundle.getString("reply");
tv.setText(response); TextView tv = findViewById(R.id.P4Result);
} tv.setText(response);
} }
endTime = System.currentTimeMillis();
TextView timetv = findViewById(R.id.P4AIRuntime);
timetv.setText("使用了" + (endTime - startTime) + "毫秒");
} }
); });
} }
private void callOtherActivity(){ private void callOtherActivity() {
EditText editText = findViewById(R.id.P4Ask); EditText editText = findViewById(R.id.P4Ask);
String request = editText.getText().toString(); String request = editText.getText().toString();
Intent intent = new Intent(this,Page4OtherActivity.class); Intent intent = new Intent(this, Page4OtherActivity.class);
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("request_content",request); bundle.putString("request_content", request);
intent.putExtras(bundle); intent.putExtras(bundle);
TextView tv = findViewById(R.id.P4Result);
tv.setText("正在询问AI");
startTime = System.currentTimeMillis();
mLauncher.launch(intent); mLauncher.launch(intent);
} }
private final class ButtonHandler implements View.OnClickListener
{
@Override
public void onClick(View v){
callOtherActivity();
}
}
@Override @Override
public boolean dispatchTouchEvent(MotionEvent ev) { public boolean dispatchTouchEvent(MotionEvent ev) {
if (getCurrentFocus() != null) { if (getCurrentFocus() != null) {
@ -87,5 +88,24 @@ public class Page4 extends AppCompatActivity {
return super.dispatchTouchEvent(ev); return super.dispatchTouchEvent(ev);
} }
private final class ButtonHandler implements View.OnClickListener {
@Override
public void onClick(View v) {
callOtherActivity();
}
}
private final class VibrateButtonHandler implements View.OnClickListener {
@Override
public void onClick(View v) {
String receivierPath = "uk.kagurach.android101.vibrationBroadcastReceiver.vibrationBroadcastReceiver";
Intent intent = new Intent(vibrationBroadcastReceiver.VIBRATION_ACTION_NAME);
ComponentName componentName = new ComponentName("uk.kagurach.android101",receivierPath);
intent.setComponent(componentName);
sendBroadcast(intent);
}
}
} }

View file

@ -16,30 +16,30 @@ public class Page4OtherActivity extends AppCompatActivity {
Bundle bundle = getIntent().getExtras(); Bundle bundle = getIntent().getExtras();
if (bundle == null) throw new NullPointerException(); if (bundle == null) throw new NullPointerException();
String content = bundle.getString("request_content"); String content = bundle.getString("request_content");
if (content!=null){ if (content != null) {
if (content.contains("想似")|| if (content.contains("想似") ||
content.contains("相似")|| content.contains("相似") ||
content.contains("相死")|| content.contains("相死") ||
content.contains("想死")){ content.contains("想死")) {
ToastHelper.SmartToast.ShowToast("不可以!",this); ToastHelper.SmartToast.ShowToast("不可以!", this);
Log.wtf("呜呜","要好好活着"); Log.wtf("呜呜", "要好好活着");
android.os.Process.killProcess(android.os.Process.myPid()); android.os.Process.killProcess(android.os.Process.myPid());
System.exit(-1); System.exit(-1);
} }
content = AIAnswerService(content); content = AIAnswerService(content);
}else { } else {
content = "对不起坏掉了"; content = "对不起坏掉了";
} }
Intent intent = new Intent(); Intent intent = new Intent();
Bundle bundle1 = new Bundle(); Bundle bundle1 = new Bundle();
bundle1.putString("reply",content); bundle1.putString("reply", content);
intent.putExtras(bundle1); intent.putExtras(bundle1);
setResult(RESULT_OK,intent); setResult(RESULT_OK, intent);
finish(); finish();
} }
} }

View file

@ -8,73 +8,70 @@ import android.content.Intent;
import android.view.View; import android.view.View;
public class PageHelper { public class PageHelper {
public final LongClickHandler longClickHandler = new LongClickHandler();
public final PageButtonHandler pageButtonHandler = new PageButtonHandler();
private final Context _curr; private final Context _curr;
private final Class<?> _prev; private final Class<?> _prev;
private final Class<?> _next; private final Class<?> _next;
private Activity _activity = null; private Activity _activity = null;
public final LongClickHandler longClickHandler = new LongClickHandler(); PageHelper(Context curr, Class<?> prev, Class<?> next) {
public final PageButtonHandler pageButtonHandler = new PageButtonHandler();
PageHelper(Context curr, Class<?> prev, Class<?> next){
_curr = curr; _curr = curr;
_prev = prev; _prev = prev;
_next = next; _next = next;
} }
PageHelper(Context curr, Class<?> prev, Class<?> next,Activity activity){ PageHelper(Context curr, Class<?> prev, Class<?> next, Activity activity) {
_curr = curr; _curr = curr;
_prev = prev; _prev = prev;
_next = next; _next = next;
_activity = activity; _activity = activity;
} }
void goPrev(){ void goPrev() {
if (_prev==null){ if (_prev == null) {
return; return;
} }
Intent myIntent = new Intent(_curr, _prev); Intent myIntent = new Intent(_curr, _prev);
startActivity(_curr,myIntent,null); startActivity(_curr, myIntent, null);
} }
void goNext(){ void goNext() {
if (_next==null){ if (_next == null) {
return; return;
} }
Intent myIntent = new Intent(_curr, _next); Intent myIntent = new Intent(_curr, _next);
startActivity(_curr,myIntent,null); startActivity(_curr, myIntent, null);
} }
void goNextFinish(){ void goNextFinish() {
if (_activity == null){ if (_activity == null) {
throw new IllegalStateException("activity is null, cannot finish the activity"); throw new IllegalStateException("activity is null, cannot finish the activity");
} }
if (_next==null){ if (_next == null) {
return; return;
} }
Intent myIntent = new Intent(_curr, _next); Intent myIntent = new Intent(_curr, _next);
startActivity(_curr,myIntent,null); startActivity(_curr, myIntent, null);
_activity.finish(); _activity.finish();
} }
private final class LongClickHandler implements View.OnLongClickListener private final class LongClickHandler implements View.OnLongClickListener {
{
@Override @Override
public boolean onLongClick(View v){ public boolean onLongClick(View v) {
goPrev(); goPrev();
return false; return false;
} }
} }
private final class PageButtonHandler implements View.OnClickListener
{ private final class PageButtonHandler implements View.OnClickListener {
@Override @Override
public void onClick(View v){ public void onClick(View v) {
if (_activity == null) { if (_activity == null) {
goNext(); goNext();
}else { } else {
goNextFinish(); goNextFinish();
} }
} }

View file

@ -3,24 +3,25 @@ package uk.kagurach.android101
import android.content.Context import android.content.Context
import android.widget.Toast import android.widget.Toast
class ToastHelper(text: String,ctx: Context) { class ToastHelper(text: String, ctx: Context) {
val _text = text val _text = text
val _ctx = ctx val _ctx = ctx
companion object SmartToast { companion object SmartToast {
fun ShowToast(text: String,ctx: Context){ fun ShowToast(text: String, ctx: Context) {
val helper = ToastHelper(text,ctx) val helper = ToastHelper(text, ctx)
helper.autoShow() helper.autoShow()
} }
} }
fun autoShow(){
if (_text.contains('\n')){ fun autoShow() {
for (line in _text.split('\n')){ if (_text.contains('\n')) {
Toast.makeText(_ctx,line,Toast.LENGTH_SHORT).show() for (line in _text.split('\n')) {
Thread.sleep(Toast.LENGTH_SHORT.toLong()+5) Toast.makeText(_ctx, line, Toast.LENGTH_SHORT).show()
Thread.sleep(Toast.LENGTH_SHORT.toLong() + 5)
} }
}else{ } else {
Toast.makeText(_ctx,_text,Toast.LENGTH_LONG).show() Toast.makeText(_ctx, _text, Toast.LENGTH_LONG).show()
} }
} }

View file

@ -45,6 +45,7 @@ import androidx.core.content.ContextCompat
import uk.kagurach.android101.R import uk.kagurach.android101.R
import uk.kagurach.android101.todoList.ui.theme.LightBlue100 import uk.kagurach.android101.todoList.ui.theme.LightBlue100
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.Locale
class AddPage() : ComponentActivity() { class AddPage() : ComponentActivity() {
@ -73,12 +74,12 @@ class AddPage() : ComponentActivity() {
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun AddPageLayout(){ fun AddPageLayout() {
val context = LocalContext.current val context = LocalContext.current
var title by remember { var title by remember {
mutableStateOf( mutableStateOf(
when (item){ when (item) {
null -> "" null -> ""
else -> item!!.title else -> item!!.title
} }
@ -88,8 +89,13 @@ class AddPage() : ComponentActivity() {
val timePickerState by remember { val timePickerState by remember {
mutableStateOf( mutableStateOf(
when (item){ when (item) {
null -> TimePickerState(c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE),true) null -> TimePickerState(
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE),
true
)
else -> TimePickerState( else -> TimePickerState(
item!!.dueDate.split(" ")[1].split(":")[0].toInt(), item!!.dueDate.split(" ")[1].split(":")[0].toInt(),
item!!.dueDate.split(" ")[1].split(":")[1].toInt(), item!!.dueDate.split(" ")[1].split(":")[1].toInt(),
@ -103,7 +109,7 @@ class AddPage() : ComponentActivity() {
initialDisplayedMonthMillis = System.currentTimeMillis(), initialDisplayedMonthMillis = System.currentTimeMillis(),
yearRange = 2024..2099 yearRange = 2024..2099
) )
Scaffold ( Scaffold(
topBar = { topBar = {
Surface( Surface(
modifier = Modifier modifier = Modifier
@ -148,22 +154,22 @@ class AddPage() : ComponentActivity() {
floatingActionButtonPosition = FabPosition.End, floatingActionButtonPosition = FabPosition.End,
floatingActionButton = { floatingActionButton = {
Submit { Submit {
if (title.isBlank()||datePickerState.selectedDateMillis==null){ if (title.isBlank() || datePickerState.selectedDateMillis == null) {
Toast.makeText(context,"Please Fill Every field",Toast.LENGTH_SHORT) Toast.makeText(context, "Please Fill Every field", Toast.LENGTH_SHORT)
.show() .show()
return@Submit return@Submit
} }
val loader = TodoItemLoader(context) val loader = TodoItemLoader(context)
val sdf = SimpleDateFormat("yyyy-MM-dd") val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
val todoItem = TodoItem( val todoItem = TodoItem(
loader.getLastId()+1, loader.getLastId() + 1,
title.replace("\t"," "), title.replace("\t", " "),
sdf.format(datePickerState.selectedDateMillis) + " " + sdf.format(datePickerState.selectedDateMillis) + " " +
timePickerState.hour.toString() + ":" + timePickerState.hour.toString() + ":" +
timePickerState.minute.toString() timePickerState.minute.toString()
) )
loader.changeItem(todoItem) loader.changeItem(todoItem)
val myIntent = Intent(context, MainActivity::class.java) val myIntent = Intent(context, MainActivity::class.java)
ContextCompat.startActivity(context, myIntent, null) ContextCompat.startActivity(context, myIntent, null)

View file

@ -35,51 +35,51 @@ class MainActivity : ComponentActivity() {
} }
} }
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun LayOut(tmpList : List<TodoItem>?) { fun LayOut(tmpList: List<TodoItem>?) {
val context = LocalContext.current val context = LocalContext.current
Scaffold ( Scaffold(
topBar = { topBar = {
TopAppBar( TopAppBar(
title = { Text("Simple TODO ^_^") } title = { Text("Simple TODO ^_^") }
) )
}, },
content = { content = { padding ->
padding -> Surface(
Surface( modifier = Modifier
modifier = Modifier.padding(padding) .padding(padding)
.verticalScroll(rememberScrollState()) .verticalScroll(rememberScrollState())
) { ) {
if (tmpList != null) { if (tmpList != null) {
Column { Column {
for (i in tmpList) { for (i in tmpList) {
TodoItemView(todoItem = i) TodoItemView(todoItem = i)
}
}
} }
} }
},
floatingActionButtonPosition = FabPosition.End,
floatingActionButton = {
NextPage {
val myIntent = Intent(context, AddPage::class.java)
ContextCompat.startActivity(context, myIntent, null)
} }
}, }
) },
floatingActionButtonPosition = FabPosition.End,
floatingActionButton = {
NextPage {
val myIntent = Intent(context, AddPage::class.java)
ContextCompat.startActivity(context, myIntent, null)
}
},
)
}
@Composable
fun NextPage(onClick: () -> Unit) {
FloatingActionButton(
onClick = { onClick() },
containerColor = LightBlue100
) {
Icon(Icons.Filled.Add, "Floating action button.")
} }
}
@Composable
fun NextPage(onClick: () -> Unit) {
FloatingActionButton(
onClick = { onClick() },
containerColor = LightBlue100
) {
Icon(Icons.Filled.Add, "Floating action button.")
}
}

View file

@ -11,7 +11,7 @@ data class TodoItem(
var title: String, var title: String,
var dueDate: String, var dueDate: String,
var isCompleted:Boolean = false, var isCompleted: Boolean = false,
var MarkDeleted:Boolean = false var MarkDeleted: Boolean = false
) )

View file

@ -6,38 +6,38 @@ import java.io.File
import java.io.FileWriter import java.io.FileWriter
class TodoItemLoader(private val context: Context) { class TodoItemLoader(private val context: Context) {
private val db = File(context.filesDir,"db") private val db = File(context.filesDir, "db")
public fun getTodoItems(): List<TodoItem>?{ public fun getTodoItems(): List<TodoItem>? {
if (!db.exists()){ if (!db.exists()) {
return null return null
} }
val lines = db.readLines() val lines = db.readLines()
if (lines.isEmpty()){ if (lines.isEmpty()) {
return null return null
} }
var list: List<TodoItem> = listOf() var list: List<TodoItem> = listOf()
for (line in lines){ for (line in lines) {
val split = line.split("\t") val split = line.split("\t")
val item: TodoItem val item: TodoItem
try { try {
item = TodoItem(split[0].toInt(),split[1],split[2], split[3].toBooleanStrict()) item = TodoItem(split[0].toInt(), split[1], split[2], split[3].toBooleanStrict())
list = list + item list = list + item
} catch (e: Exception){ } catch (e: Exception) {
Log.e("DB Error", e.printStackTrace().toString()) Log.e("DB Error", e.printStackTrace().toString())
} }
} }
if (list.isNotEmpty()){ if (list.isNotEmpty()) {
return list return list
} }
return null return null
} }
public fun saveTodoItems(list:List<TodoItem>){ public fun saveTodoItems(list: List<TodoItem>) {
var result = "" var result = ""
for (i in list){ for (i in list) {
if(!i.MarkDeleted) { if (!i.MarkDeleted) {
result += "%s\t%s\t%s\t%s\n".format( result += "%s\t%s\t%s\t%s\n".format(
i.id.toString(), i.id.toString(),
i.title, i.title,
@ -51,14 +51,14 @@ class TodoItemLoader(private val context: Context) {
fileWriter.close() fileWriter.close()
} }
public fun getLastId():Int{ public fun getLastId(): Int {
val items = getTodoItems(); val items = getTodoItems();
return if (items==null){ return if (items == null) {
0 0
}else{ } else {
var max = 0 var max = 0
for (i in items){ for (i in items) {
if (i.id>max){ if (i.id > max) {
max = i.id max = i.id
} }
} }
@ -66,12 +66,12 @@ class TodoItemLoader(private val context: Context) {
} }
} }
public fun changeItem(todoItem: TodoItem){ public fun changeItem(todoItem: TodoItem) {
var items = getTodoItems() var items = getTodoItems()
var changeFlag = false var changeFlag = false
if (items != null) { if (items != null) {
for (i in items){ for (i in items) {
if (i.id==todoItem.id){ if (i.id == todoItem.id) {
i.title = todoItem.title i.title = todoItem.title
i.dueDate = todoItem.dueDate i.dueDate = todoItem.dueDate
i.MarkDeleted = todoItem.MarkDeleted i.MarkDeleted = todoItem.MarkDeleted
@ -80,22 +80,22 @@ class TodoItemLoader(private val context: Context) {
break break
} }
} }
if (!changeFlag){ if (!changeFlag) {
items = items + todoItem items = items + todoItem
} }
}else{ } else {
items = listOf(todoItem) items = listOf(todoItem)
} }
saveTodoItems(items) saveTodoItems(items)
} }
public fun searchItem(id:Int): TodoItem?{ public fun searchItem(id: Int): TodoItem? {
val items = getTodoItems(); val items = getTodoItems();
return if (items==null){ return if (items == null) {
null null
}else{ } else {
for (i in items){ for (i in items) {
if (i.id>id){ if (i.id > id) {
return i return i
} }
} }

View file

@ -42,7 +42,7 @@ fun TodoItemView(todoItem: TodoItem) {
} }
var bgColor by remember { var bgColor by remember {
mutableStateOf( mutableStateOf(
when (todoItem.isCompleted){ when (todoItem.isCompleted) {
true -> Green100 true -> Green100
false -> Blue100 false -> Blue100
} }
@ -51,7 +51,7 @@ fun TodoItemView(todoItem: TodoItem) {
var needShow by remember { var needShow by remember {
mutableStateOf(true) mutableStateOf(true)
} }
if (!needShow){ if (!needShow) {
return return
} }
@ -68,14 +68,14 @@ fun TodoItemView(todoItem: TodoItem) {
start = 10.dp, start = 10.dp,
end = 10.dp end = 10.dp
) )
){ ) {
Text( Text(
text = todoItem.title, text = todoItem.title,
color = Color.Black, color = Color.Black,
fontSize = 30.sp, fontSize = 30.sp,
fontFamily = FontFamily.Monospace fontFamily = FontFamily.Monospace
) )
Row{ Row {
Spacer(modifier = Modifier.weight(1f)) Spacer(modifier = Modifier.weight(1f))
Text( Text(
text = todoItem.dueDate, text = todoItem.dueDate,
@ -87,11 +87,12 @@ fun TodoItemView(todoItem: TodoItem) {
Row { Row {
TextButton( TextButton(
onClick = { onClick = {
if (!todoItem.isCompleted){ if (!todoItem.isCompleted) {
Toast.makeText( context, Toast.makeText(
context.getText(R.string.yes_not_finish) context,
,Toast.LENGTH_SHORT).show() context.getText(R.string.yes_not_finish), Toast.LENGTH_SHORT
}else{ ).show()
} else {
todoItem.isCompleted = false todoItem.isCompleted = false
loader.changeItem(todoItem) loader.changeItem(todoItem)
bgColor = Blue100 bgColor = Blue100
@ -105,11 +106,12 @@ fun TodoItemView(todoItem: TodoItem) {
Spacer(modifier = Modifier.width(20.dp)) Spacer(modifier = Modifier.width(20.dp))
TextButton( TextButton(
onClick = { onClick = {
if (todoItem.isCompleted){ if (todoItem.isCompleted) {
Toast.makeText( context, Toast.makeText(
context.getText(R.string.already_finish) context,
,Toast.LENGTH_SHORT).show() context.getText(R.string.already_finish), Toast.LENGTH_SHORT
}else{ ).show()
} else {
todoItem.isCompleted = true todoItem.isCompleted = true
loader.changeItem(todoItem) loader.changeItem(todoItem)
bgColor = Green100 bgColor = Green100
@ -123,9 +125,10 @@ fun TodoItemView(todoItem: TodoItem) {
Spacer(modifier = Modifier.width(20.dp)) Spacer(modifier = Modifier.width(20.dp))
TextButton( TextButton(
onClick = { onClick = {
when (deleteText){ when (deleteText) {
context.getText(R.string.first_delete).toString() -> context.getText(R.string.first_delete).toString() ->
deleteText=context.getText(R.string.second_delete).toString() deleteText = context.getText(R.string.second_delete).toString()
else -> { else -> {
needShow = false needShow = false
todoItem.MarkDeleted = true todoItem.MarkDeleted = true
@ -147,12 +150,12 @@ fun TodoItemView(todoItem: TodoItem) {
@Preview(showBackground = true) @Preview(showBackground = true)
@Composable @Composable
fun TodoItemPreview(){ fun TodoItemPreview() {
val todoItem = TodoItem( val todoItem = TodoItem(
0,"Test TODO Item","2024-04-30 11:45", 0, "Test TODO Item", "2024-04-30 11:45",
) )
val todoItem2 = TodoItem( val todoItem2 = TodoItem(
1,"测试喵","2024-11-01 22:33",true 1, "测试喵", "2024-11-01 22:33", true
) )
Column { Column {
TodoItemView(todoItem) TodoItemView(todoItem)
@ -160,8 +163,8 @@ fun TodoItemPreview(){
} }
} }
fun NextPage(context:Context,item: TodoItem) { fun NextPage(context: Context, item: TodoItem) {
val myIntent = Intent(context, AddPage::class.java) val myIntent = Intent(context, AddPage::class.java)
myIntent.putExtra("ITEM",item.id) myIntent.putExtra("ITEM", item.id)
ContextCompat.startActivity(context, myIntent, null) ContextCompat.startActivity(context, myIntent, null)
} }

View file

@ -0,0 +1,30 @@
package uk.kagurach.android101.vibrationBroadcastReceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.CombinedVibration;
import android.os.VibrationEffect;
import android.os.VibratorManager;
import android.util.Log;
import java.util.Objects;
public class vibrationBroadcastReceiver extends BroadcastReceiver {
public static final String VIBRATION_ACTION_NAME = "uk.kagurach.android101.vibrationBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if (Objects.equals(intent.getAction(), VIBRATION_ACTION_NAME)) {
VibratorManager vibrator = (VibratorManager) context.getSystemService(
Context.VIBRATOR_MANAGER_SERVICE
);
vibrator.vibrate(
CombinedVibration.createParallel(
VibrationEffect.createOneShot(1500,VibrationEffect.DEFAULT_AMPLITUDE)
));
Log.d("Debug","Vibrate!");
}
}
}

View file

@ -4,58 +4,60 @@ import java.time.Instant
import java.util.Date import java.util.Date
import kotlin.random.Random import kotlin.random.Random
fun AIAnswerService(s: String):String { fun AIAnswerService(s: String): String {
val rng = Random(Date.from(Instant.now()).time) val rng = Random(Date.from(Instant.now()).time)
var result = s var result = s
result = result.replace("","?") result = result.replace("", "?")
val isMoral = s.contains("") val isMoral = s.contains("")
val needAI = s.contains("") val needAI = s.contains("")
result = result.replace("","^") result = result.replace("", "^")
result = result.replace("","") result = result.replace("", "")
result = result.replace("","@") result = result.replace("", "@")
if (isMoral){ if (isMoral) {
result = if (rng.nextBoolean()) { result = if (rng.nextBoolean()) {
"谢谢@的提问,$result" "谢谢@的提问,$result"
} else{ } else {
if (result.endsWith(".")|| if (result.endsWith(".") ||
result.endsWith("")|| result.endsWith("") ||
result.endsWith("?")){ result.endsWith("?")
) {
result = result.dropLast(1); result = result.dropLast(1);
} }
"$result,谢谢。" "$result,谢谢。"
} }
result = result.replace("","") result = result.replace("", "")
} }
if (needAI){ if (needAI) {
result = result.replace("","") result = result.replace("", "")
} }
result = result.replace("", result = result.replace(
if (rng.nextBoolean()){ "",
if (rng.nextBoolean()) {
"可以" "可以"
}else{ } else {
"不可以" "不可以"
} }
) )
result = result.replace("什么","很多") result = result.replace("什么", "很多")
result = result.replace("","") result = result.replace("", "")
result = result.replace("?","") result = result.replace("?", "")
result = result.replace("^","") result = result.replace("^", "")
result = result.replace("@","") result = result.replace("@", "")
return result return result
} }
fun main(){ fun main() {
println(AIAnswerService("我想吃饭")) println(AIAnswerService("我想吃饭"))
println(AIAnswerService("咱可以吃饭吗")) println(AIAnswerService("咱可以吃饭吗"))
println(AIAnswerService("您可以做什么?")) println(AIAnswerService("您可以做什么?"))

View file

@ -31,7 +31,6 @@
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="1" android:layout_weight="1"
android:text="@string/next_page" android:text="@string/next_page"
android:onClick="jumpToNext"
android:enabled="false" android:enabled="false"
/> />

View file

@ -20,15 +20,18 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:textSize="40sp" android:textSize="40sp"
android:text="@string/user"/> android:text="@string/user"/>
<EditText <EditText
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="200dp" android:layout_height="wrap_content"
android:textSize="40sp" android:textSize="35sp"
android:id="@+id/P4Ask" android:id="@+id/P4Ask"
android:importantForAutofill="no" android:importantForAutofill="no"
android:text="你吃了吗?" android:text="@string/AI_ASK_DEFAULT_STRING"
android:textColor="@color/tfp" android:textColor="@color/tfp"
android:hint="@string/AI_ASK_DEFAULT_STRING"
android:inputType="text" /> android:inputType="text" />
<View <View
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="50dp" /> android:layout_height="50dp" />
@ -38,14 +41,23 @@
android:textSize="40sp" android:textSize="40sp"
android:text="@string/ai"/> android:text="@string/ai"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="300dp">
<TextView
android:layout_width="match_parent"
android:textSize="35sp"
android:layout_height="wrap_content"
android:id="@+id/P4Result"
android:textColor="@color/tfb"
/>
</ScrollView>
<TextView <TextView
android:layout_width="match_parent" android:layout_width="match_parent"
android:textSize="40sp" android:layout_height="wrap_content"
android:layout_height="200dp" android:textSize="25sp"
android:id="@+id/P4Result" android:id="@+id/P4AIRuntime"
android:textColor="@color/tfb" android:text="@string/ai_ready"/>
/>
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
@ -57,6 +69,14 @@
android:id="@+id/P4AskAI" android:id="@+id/P4AskAI"
android:text="@string/ask_ai" android:text="@string/ask_ai"
/> />
<Button
android:layout_width="140dp"
android:layout_height="match_parent"
android:id="@+id/P4Vibrate"
android:text="@string/vibrate"
/>
<Button <Button
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"

View file

@ -14,4 +14,7 @@
<string name="user">用户</string> <string name="user">用户</string>
<string name="ai">AI</string> <string name="ai">AI</string>
<string name="ask_ai">询问AI</string> <string name="ask_ai">询问AI</string>
<string name="ai_ready">AI 准备好了</string>
<string name="AI_ASK_DEFAULT_STRING">你吃了吗?</string>
<string name="vibrate">振动手机</string>
</resources> </resources>

View file

@ -24,4 +24,7 @@
<string name="user">User</string> <string name="user">User</string>
<string name="ai">AI</string> <string name="ai">AI</string>
<string name="ask_ai">ASK AI</string> <string name="ask_ai">ASK AI</string>
<string name="ai_ready">AI Ready</string>
<string name="AI_ASK_DEFAULT_STRING">你吃了吗?</string>
<string name="vibrate">Vibrate</string>
</resources> </resources>

View file

@ -1,24 +1,24 @@
[versions] [versions]
agp = "8.3.2" agp = "8.3.2"
kotlin = "1.9.0" kotlin = "1.9.0"
coreKtx = "1.13.0" coreKtx = "1.13.1"
junit = "4.13.2" junit = "4.13.2"
junitVersion = "1.1.5" junitVersion = "1.1.5"
espressoCore = "3.5.1" espressoCore = "3.5.1"
appcompat = "1.6.1" appcompat = "1.6.1"
material = "1.11.0" material = "1.12.0"
activity = "1.9.0" activity = "1.9.0"
constraintlayout = "2.1.4" constraintlayout = "2.1.4"
lifecycleRuntimeKtx = "2.7.0" lifecycleRuntimeKtx = "2.8.0"
activityCompose = "1.9.0" activityCompose = "1.9.0"
composeBom = "2024.04.01" composeBom = "2024.05.00"
roomCommon = "2.6.1" roomCommon = "2.6.1"
roomKtx = "2.6.1" roomKtx = "2.6.1"
navigationFragmentKtx = "2.7.7" navigationFragmentKtx = "2.7.7"
navigationUiKtx = "2.7.7" navigationUiKtx = "2.7.7"
annotation = "1.7.1" annotation = "1.8.0"
lifecycleLivedataKtx = "2.7.0" lifecycleLivedataKtx = "2.8.0"
lifecycleViewmodelKtx = "2.7.0" lifecycleViewmodelKtx = "2.8.0"
[libraries] [libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }