android记事本代码
时间: 2023-11-22 12:04:19 浏览: 64
Android记事本程序代码
5星 · 资源好评率100%
以下是一个简单的Android记事本应用程序的代码示例。你可以根据自己的需求和喜好进行修改和优化。
MainActivity.java
```
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
private EditText mEditText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText) findViewById(R.id.editText);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
saveText();
return true;
case R.id.menu_load:
loadText();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void saveText() {
try {
FileOutputStream fileOut = openFileOutput("note.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fileOut);
outputWriter.write(mEditText.getText().toString());
outputWriter.close();
Toast.makeText(this, "Note saved!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadText() {
try {
FileInputStream fileIn = openFileInput("note.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileIn);
char[] inputBuffer = new char[100];
String s = "";
int charRead;
while ((charRead = inputStreamReader.read(inputBuffer)) > 0) {
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
}
inputStreamReader.close();
mEditText.setText(s);
Toast.makeText(this, "Note loaded!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
activity_main.xml
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:gravity="top"
android:hint="Write your note here"
android:padding="10dp"
android:textSize="16sp" />
</RelativeLayout>
```
menu_main.xml
```
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_save"
android:icon="@drawable/ic_menu_save"
android:title="Save" />
<item
android:id="@+id/menu_load"
android:icon="@drawable/ic_menu_load"
android:title="Load" />
</menu>
```
请注意,在使用此代码之前,你需要在项目的AndroidManifest.xml文件中添加以下权限:
```
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
阅读全文