Android - 尝试创建“先保存文件?”对话框

时间:2013-02-15 00:59:20

标签: java android dialog

我的应用程序包含一个文本文件列表。单击文件会将其加载到EditText中。我创建了一个选项菜单来保存打开的文件,或者保存就像处理新文件一样。我想做的是显示“先保存?”如果用户尝试打开新文件而不先保存打开的文件,则确认对话框。

正如您在下面的代码中看到的,我创建了一个名为changed的布尔变量,最初初始化为false。我正在尝试使用TextChangedListener将更改更改为true,然后使用列表的文件打开代码中的if / else语句处理它。我遇到的问题是,一旦我打开一个文件,然后尝试打开另一个文件,它会显示“保存第一个”对话框,但无论文件是否被更改,或者我是否单击确定或取消它都不会打开任何文件其他文件。

public class MainActivity extends ListActivity {

private List<String> items = null;
public File currentDir = null;
public File currentFile = null;
public EditTextLineNumbers et; // My EditText
public boolean changed = false;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        checkExternalStorage();
        File dir = new File(Environment.getExternalStorageDirectory() + "/My Webs");
        currentDir = dir;
        et = (EditTextLineNumbers) findViewById(R.id.ide);
        et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                changed = true;
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                changed=false;

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
        if(dir.isDirectory()) {
            getFiles(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Webs").listFiles());
        }else{
            dir.mkdir();
        }
    }

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu, menu);
            return true;
        }

    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if(item.getItemId()== R.id.newsite){
                Log.d("New Site","New Site was clicked");
            }else if(item.getItemId()== R.id.newfile){
                Log.d("New File","New File was clicked");
            }else if(item.getItemId()== R.id.savefile){
                String temptxt = et.getText().toString();

                if(currentFile!=null){
                    Log.d(currentFile.getAbsolutePath(),currentFile.getAbsolutePath());
                    String tempfname = currentFile.toString();
                    saveFile(tempfname, temptxt);
                }else{
                    saveFile(null, temptxt);
                }

            }
            return super.onOptionsItemSelected(item);
        }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id){
        int selectedRow = (int)id;
        if(selectedRow == 0){
            getFiles(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Webs").listFiles());
        }else{
            File file = new File(items.get(selectedRow));
            if(file.isDirectory()){
                currentDir = file;
                getFiles(file.listFiles());
            }else{
                currentFile = file;
            if(changed==false){
                try {
                    et.setText(new Scanner(file).useDelimiter("\\Z").next());
                    } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    }   
                }else{
                    AlertDialog.Builder alert = new AlertDialog.Builder(this);

                    alert.setTitle("Save first");
                    alert.setMessage("(Will be saved in the current working directory)");

                    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                      String tmpText = et.getText().toString();

                      try {
                        File tempfile = new File(currentDir, currentFile.toString());
                        FileWriter writer = new FileWriter(tempfile);
                          writer.write(tmpText);
                          writer.flush();
                          writer.close();

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                      }
                    });

                    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int whichButton) {
                        // Canceled.
                      }
                    });

                    alert.show();

                }
            }
            }
        }


    private void saveFile(String sFileName, String sBody){

        if (currentFile!=null) {
            try {
                File saveDir = new File("/");

                File tempfile = new File(saveDir, sFileName);
                FileWriter writer = new FileWriter(tempfile);
                writer.append(sBody);
                writer.flush();
                writer.close();

                Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            saveAs();
        }

    }

    private void saveAs(){
        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("Save as");
        alert.setMessage("(Will be saved in the current working directory)");

        // Set an EditText view to get user input 
        final EditText input = new EditText(this);
        alert.setView(input);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
          String value = input.getText().toString();
          String tmpText = et.getText().toString();

          try {
            File tempfile = new File(currentDir, value);
            FileWriter writer = new FileWriter(tempfile);
              writer.write(tmpText);
              writer.flush();
              writer.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
            // Canceled.
          }
        });

        alert.show();
    }
        private void getFiles(File[] files){
            items = new ArrayList<String>();
            items.add(getString(R.string.goto_root));
            for(File file : files){
                String filename = file.getName().toString();
                String filenameArray[] = filename.split("\\.");
                String extension = filenameArray[filenameArray.length-1];
                Log.d("Extension", extension);
                items.add(file.getPath());
            }
            ArrayAdapter<String> fileList = new ArrayAdapter<String>(this,R.layout.row_item, items);
            setListAdapter(fileList);
        }

}

2 个答案:

答案 0 :(得分:1)

如果文字发生变化,您的变量change将始终为true,因为事件beforeTextChanged将在onTextChanged被触发后首先被调用。

  

beforeTextChanged(CharSequence s,int start,int count,int after)   调用此方法是为了通知您,在s中,从start开始的计数字符将被替换为长度为的新文本。

     

onTextChanged(CharSequence s,int start,int before,int count)   调用此方法是为了通知您,在s中,从start开始的计数字符刚刚替换了之前具有长度的旧文本。

保存文件后,您应该将变量change 重置设为false

if(!changed){
    // open the file
 }else{
    changed = false;
    // show the alert and save the file
 }

答案 1 :(得分:0)

此处et.setText(new Scanner(file).useDelimiter("\\Z").next());您更改了文字。此时,更改为true

在EditText中加载测试后,需要将其设置回false