android studio 记事本代码
时间: 2023-09-20 14:07:32 浏览: 143
以下是一个简单的记事本应用程序的代码示例,你可以在 Android Studio 中使用它进行开发:
MainActivity.java
```java
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
private EditText mEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = findViewById(R.id.edit_text);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_save) {
saveFile();
return true;
} else if (id == R.id.action_open) {
openFile();
return true;
}
return super.onOptionsItemSelected(item);
}
private void saveFile() {
String fileName = "note.txt";
String text = mEditText.getText().toString();
try {
FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void openFile() {
String fileName = "note.txt";
try {
FileInputStream fis = openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
mEditText.setText(sb.toString());
br.close();
isr.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
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="match_parent"
android:gravity="top|start"
android:scrollbars="vertical"
android:padding="16dp"/>
</LinearLayout>
```
menu_main.xml
```xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/action_save"
android:title="Save"
android:icon="@drawable/ic_save"
app:showAsAction="ifRoom"/>
<item android:id="@+id/action_open"
android:title="Open"
android:icon="@drawable/ic_folder"
app:showAsAction="ifRoom"/>
</menu>
```
注:此代码仅供参考,实际开发中可能需要进行修改和完善。
阅读全文