0

我的应用程序包含一个文本文件列表。单击文件会将其加载到 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);
        }

}

4

2 回答 2

1

如果文本更改,您的变量change将始终是true,因为该事件beforeTextChanged将首先被调用,然后onTextChanged将被触发。

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

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

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

if(!changed){
    // open the file
 }else{
    changed = false;
    // show the alert and save the file
 }
于 2013-02-15T01:12:45.930 回答
0

在这里et.setText(new Scanner(file).useDelimiter("\\Z").next());更改文本。此时,changed 变为true

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

于 2014-02-28T20:39:31.810 回答