由此動作要產生AlertDialog
並提供兩個選項讓user操作
1. Edit (編輯.txt檔的內容)
2. Delete (刪除此.txt檔)DialogInterface.OnClickListener lvEditItem_DI;
AlertDialog lvEditItem_AD;
ListView.setOnItemLongClickListener(new OnItemLongClickListener()
{
@Override
public boolean onItemLongClick(final AdapterView<?> arg0, View arg1, final int arg2, long arg3)
{
AlertDialog.Builder a = new AlertDialog.Builder(context);
a.setTitle("title");
a.setItems(R.array.lv_item_options, lvEditItem_DI);
lvEditItem_AD = a.create();
lvEditItem_AD.show();
實作選單內容
return false;
}
});
=====粗體的部份要以function來實作, 好處是使code看起來更規律&能重複使用=====
實作選單內容
public void funImplementEdit(final AdapterView<?> arg0, final int arg2, final AlertDialog lvEditItem_AD)
{
lvEditItem_DI = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
switch(which)
{
case 0: //編輯檔案
//再建立一個AlertDialog作為編輯畫面
AlertDialog.Builder mADB = new AlertDialog.Builder(context);
LayoutInflater factory = LayoutInflater.from(context);
//layout_filecontent裡包含了EditText, Button
final View view = factory.inflate(R.layout.layout_filecontent, null);
mADB.setView(view);
final EditText et_name = (EditText) view.findViewById(R.id.et_name);
final EditText et_content = (EditText) view.findViewById(R.id.et_content);
Button bt_ok = (Button) view.findViewById(R.id.bt_ok);
Button bt_no = (Button) view.findViewById(R.id.bt_no);
final AlertDialog mAD = mADB.create();
mAD.show();
//讀取檔名
et_name.setText(arg0.getItemAtPosition(arg2).toString());
//讀取檔案內容
try
{
String wroteFilePath = savePath+"/"+et_name.getText().toString();
InputStream input = new BufferedInputStream(new FileInputStream(wroteFilePath));
int res2 = input.available();
byte [] by2 = new byte[res2];
input.read(by2);
//把類型設為UTF-8才能正常讀取中文字!
String re2 = EncodingUtils.getString(by2, "UTF-8");
et_content.setText(re2);}
catch (IOException e)
{
e.printStackTrace();
}
//編輯完.txt檔內容按下「ok」 Button才會儲存
bt_ok.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//原始檔案File
File oldFile = new File( savePath+"/"+arg0.getItemAtPosition(arg2) );
String newFilePath = savePath+"/"+et_name.getText();
//修改檔名
oldFile.renameTo(new File(newFilePath));
//編輯檔案內容
FileWriter wFile;
try
{
wFile = new FileWriter( savePath+"/"+et_name.getText() );
wFile.write(et_content.getText().toString());
wFile.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//重新載入list data
funLoadListData();
//關閉Dialog
mAD.dismiss();
}
});
//編輯完.txt檔內容按下「no」 Button則不做任何變更
bt_no.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//關閉Dialog
mAD.dismiss();
}
});
break;
case 1: //刪除檔案
File oldFile = new File( savePath+"/"+arg0.getItemAtPosition(arg2) );
oldFile.delete();
//重新載入list data
funLoadListData();
//關閉Dialog
lvEditItem_AD.dismiss();
break;
}
}
};
}
沒有留言:
張貼留言