一个简单的android便签app
MainActivity.java
package com.zp.myfirstapp;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.zp.myfirstapp.R;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener,
OnItemClickListener, OnItemLongClickListener {
private Button add_bt;
private ListView listV;
private MyAdapter adapter;
private List<Map<String, Object>> data_list;
private FragmentManager manager;
private OptionMenu menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
RefreshItem();
}
//重新加载listview
private void RefreshItem() {
data_list.clear();
String filePath = this.getFilesDir().toString();
File folder = new File(filePath);
File[] file = folder.listFiles();
ArrayList<String> filenamelist = new ArrayList<String>();
for (int i = 0; i < file.length; i++) {
filenamelist.add(file[i].getAbsolutePath());
}
//降序
//Collections.sort(filenamelist,Collections.reverseOrder());
//升序
Collections.sort(filenamelist);
for (int i = 0; i < file.length; i++) {
File filex = new File(filenamelist.get(i));
String content = RWFile.readFile(filex);
Map<String, Object> map = new HashMap<String, Object>();
map.put("content", content);
map.put("filename", getFileName(filex));
map.put("isChecked", Boolean.FALSE);
data_list.add(map);
}
adapter.notifyDataSetChanged();
}
//获取文件名
public String getFileFullName(File file) {
String path = file.getAbsolutePath();
int index = path.lastIndexOf("/") + 1;
String filefullname = path.substring(index);
return filefullname;
}
public String getFileName(File file) {
String filefullname = getFileFullName(file);
int index = filefullname.lastIndexOf(".");
String filename = filefullname.substring(0, index);
return filename;
}
//初始化数据
private void init() {
add_bt = (Button) findViewById(R.id.add_bt);
add_bt.setOnClickListener(this);
listV = (ListView) findViewById(R.id.ListView);
data_list = new ArrayList<Map<String, Object>>();
adapter = new MyAdapter(this, data_list);
listV.setAdapter(adapter);
listV.setOnItemClickListener(this);
listV.setOnItemLongClickListener(this);
this.registerForContextMenu(listV);
manager = getFragmentManager();
}
//设置按钮点击事件
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add_bt: {
Intent intent = new Intent(this, EditorActivity.class);
startActivityForResult(intent, 0);
break;
}
}
}
// 根据返回值执行不同事件
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
switch (resultCode) {
case 0: {
RefreshItem();
break;
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
//设置item点击事件
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) adapter
.getItem(position);
Intent intent = new Intent(MainActivity.this, EditorActivity.class);
Bundle bundle = new Bundle();
bundle.putString("filename", map.get("filename").toString());
intent.putExtras(bundle);
startActivityForResult(intent, 0);
}
//设置item长按事件
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
menu = new OptionMenu();
if(manager.getBackStackEntryCount()==0){
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.LinearLayout, menu);
transaction.addToBackStack(null);
transaction.commit();
}
adapter.setVisiblity(true);
adapter.notifyDataSetChanged();
add_bt.setVisibility(View.GONE);
return true;
}
//按钮事件
public void doclick(View view) {
switch (view.getId()) {
case R.id.SA_bt:
for (int i = 0; i < data_list.size(); i++) {
data_list.get(i).put("isChecked", true);
}
adapter.notifyDataSetChanged();
break;
case R.id.SN_bt:
for (int i = 0; i < data_list.size(); i++) {
data_list.get(i).put("isChecked", false);
}
adapter.notifyDataSetChanged();
break;
case R.id.RS_bt:
for (int i = 0; i < data_list.size(); i++) {
if ((Boolean) data_list.get(i).get("isChecked")) {
data_list.get(i).put("isChecked", false);
} else {
data_list.get(i).put("isChecked", true);
}
}
adapter.notifyDataSetChanged();
break;
case R.id.del_bt:
for (int i = 0; i < data_list.size(); i++) {
if ((Boolean) data_list.get(i).get("isChecked")) {
String filepath = this.getFilesDir().toString() + "/"
+ data_list.get(i).get("filename") + ".txt";
File file = new File(filepath);
file.delete();
}
}
RefreshItem();
adapter.notifyDataSetChanged();
case R.id.cal_bt:
add_bt.setVisibility(View.VISIBLE);
onBackPressed();
adapter.setVisiblity(false);
adapter.notifyDataSetChanged();
break;
}
}
//设置返回按钮事件
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
onBackPressed();
add_bt.setVisibility(View.VISIBLE);
adapter.setVisiblity(false);
adapter.notifyDataSetChanged();
break;
}
return false;
}
}
EditorActivity.java
package com.zp.myfirstapp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.zp.myfirstapp.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class EditorActivity extends Activity implements OnClickListener {
private Button save_bt, del_bt;
private EditText editT;
private String filename;
private String content;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
intent = getIntent();
init();
getFileName();
}
//获取从MainActivity中传过来的文件名
private void getFileName() {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if (bundle != null) {
filename = bundle.get("filename") + ".txt";
File file = new File(this.getFilesDir() + "/" + filename);
editT.setText(RWFile.readFile(file));
editT.setSelection(editT.getText().length());
}
}
//初始化数据
private void init() {
// TODO Auto-generated method stub
save_bt = (Button) findViewById(R.id.save_bt);
del_bt = (Button) findViewById(R.id.del_bt);
save_bt.setOnClickListener(this);
del_bt.setOnClickListener(this);
editT = (EditText) findViewById(R.id.EditText);
//获取当前时间,并设置为文件名
SimpleDateFormat sDateFormat = new SimpleDateFormat(
"yyyy-MM-dd-hh-mm-ss");
String date = sDateFormat.format(new Date());
filename = date + ".txt";
}
//按钮点击的事件
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.save_bt: {
content = editT.getText().toString();
if (!content.equals("")) {
RWFile.writeFile(this.getFilesDir() + "/" + filename, content);
setResult(0);
} else
setResult(1);
finish();
break;
}
case R.id.del_bt: {
setResult(1);
finish();
break;
}
}
}
//如果内容不为空,则保存为txt文件
public void saveText(String str) throws IOException {
if (!str.equals("")) {
FileOutputStream output = openFileOutput(filename, MODE_PRIVATE);
output.write(str.getBytes());
output.close();
}
}
//设置返回键的事件
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK: {
setResult(1, intent);
finish();
break;
}
}
return super.onKeyDown(keyCode, event);
}
}
MyAdapter.java
package com.zp.myfirstapp;
import java.util.List;
import java.util.Map;
import com.zp.myfirstapp.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter {
private Boolean visiblity = false;
private List<Map<String, Object>> list;
private LayoutInflater mInflater;
private ViewHolder holder;
public MyAdapter(Context context, List<Map<String, Object>> list) {
super();
// TODO Auto-generated constructor stub
this.list = list;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
static class ViewHolder {
public CheckBox checkB;
public TextView content;
public TextView data;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item, null);
holder.checkB = (CheckBox) convertView.findViewById(R.id.checkBox);
holder.data = (TextView) convertView.findViewById(R.id.textView2);
holder.content = (TextView) convertView
.findViewById(R.id.textView1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.content.setText(list.get(position).get("content").toString());
holder.data.setText(list.get(position).get("filename").toString());
holder.checkB.setChecked((Boolean) list.get(position).get("isChecked"));
//设置checkbox监视器,并根据checkbox的ischecked属性更改list中对应值
holder.checkB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
list.get(position).put("isChecked", isChecked);
}
});
if (visiblity)
holder.checkB.setVisibility(View.VISIBLE);
else
holder.checkB.setVisibility(View.GONE);
return convertView;
}
// 设置checkbox是否可见
public void setVisiblity(Boolean b) {
visiblity = b;
}
}
OptinMenu.java
package com.zp.myfirstapp;
import com.zp.myfirstapp.R;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OptionMenu extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view=inflater.inflate(R.layout.optionmenu, null);
return view;
}
}
RWFile.java
package com.zp.myfirstapp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.util.Log;
import android.widget.Toast;
public class RWFile {
//读txt文件
public static String readFile(File file) {
try {
FileInputStream inputStream = new FileInputStream(file);
int len=inputStream.available();
byte []buffer=new byte[len];
inputStream.read(buffer);
inputStream.close();
String content=new String(buffer);
return content;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//写txt文件
public static void writeFile(String filename,String content) {
File file = new File(filename);
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file);
outputStream.write(content.getBytes());
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
activity_editor.xml
<LinearLayout 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"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<ScrollView
android:layout_weight="9"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
<EditText
android:textSize="28sp"
android:id="@+id/EditText"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:background="@drawable/edittext_bg"
android:hint="请输入内容" />
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right" >
<Button
android:id="@+id/save_bt"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:focusable="true"
android:text="@string/save" />
<Button
android:id="@+id/del_bt"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="@string/cancel" />
</LinearLayout>
</LinearLayout>
activity_main.xml
<LinearLayout 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="${relativePackage}.${activityClass}"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/LinearLayout"
android:orientation="horizontal"
android:gravity="right">
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:id="@+id/ListView"></ListView>
<Button
android:onClick="doclick"
android:id="@+id/add_bt"
android:focusable="false"
android:layout_gravity="bottom|right"
android:background="@drawable/add_bt"
android:layout_height="60dp"
android:layout_width="60dp"/>
</FrameLayout>
</LinearLayout>
item.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">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<TextView
android:layout_weight="9"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:maxLines="2"
android:textSize="20sp" />
<CheckBox
android:tag=""
android:id="@+id/checkBox"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:focusable="false" />
</LinearLayout>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textSize="15sp" />
</LinearLayout>
optionmenu.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">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<TextView
android:layout_weight="9"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:maxLines="2"
android:textSize="20sp" />
<CheckBox
android:tag=""
android:id="@+id/checkBox"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:focusable="false" />
</LinearLayout>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textSize="15sp" />
</LinearLayout>