android 简易记事本 源代码
时间: 2023-08-26 15:07:10 浏览: 112
以下是一个简单的 Android 记事本应用的源代码,你可以参考一下:
MainActivity.java:
```java
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private EditText mEditText;
private static final String FILE_NAME = "note.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = findViewById(R.id.edit_text);
loadNote();
}
private void loadNote() {
FileInputStream fis = null;
try {
fis = openFileInput(FILE_NAME);
byte[] data = new byte[fis.available()];
fis.read(data);
String note = new String(data);
mEditText.setText(note);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void saveNote() {
FileOutputStream fos = null;
try {
fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
String note = mEditText.getText().toString();
fos.write(note.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void onSaveButtonClick(View view) {
saveNote();
}
}
```
activity_main.xml:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:hint="@string/note_hint"
android:gravity="top|start"
android:padding="16dp"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<Button
android:id="@+id/save_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="16dp"
android:text="@string/save_button_text"
android:onClick="onSaveButtonClick" />
</LinearLayout>
```
strings.xml:
```xml
<resources>
<string name="app_name">Simple Note</string>
<string name="note_hint">Type your note here...</string>
<string name="save_button_text">Save</string>
</resources>
```
请注意:这只是一个简单的示例应用,没有实现任何其他功能(如读取和编辑笔记、添加标题等)。
阅读全文