【问题标题】:Android - getting back to menu from filepicker/browsing screenAndroid - 从文件选择器/浏览屏幕返回菜单
【发布时间】:2012-08-23 15:23:34
【问题描述】:

我在网上找到了这个文件选择器,开发人员说人们可以根据需要使用它。 因为我认为代码很容易理解 - 我决定使用它并为我的应用程序稍微改变它。 所有功劳归于原始开发者 (https://github.com/mburman/Android-File-Explore)

        loadFileList();

    showDialog(DIALOG_LOAD_FILE);
    Log.d(TAG, path.getAbsolutePath());

}

private void loadFileList() {
    try {
        path.mkdirs();
    } catch (SecurityException e) {
        Log.e(TAG, "unable to write on the sd card ");
    }

    // Checks whether path exists
    if (path.exists()) {
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String filename) {
                File sel = new File(dir, filename);
                // Filters based on whether the file is hidden or not
                return (sel.isFile() || sel.isDirectory())
                        && !sel.isHidden();

            }
        };

        String[] fList = path.list(filter);
        fileList = new Item[fList.length];
        for (int i = 0; i < fList.length; i++) {
            fileList[i] = new Item(fList[i], R.drawable.file_icon);

            // Convert into file path
            File sel = new File(path, fList[i]);

            // Set drawables
            if (sel.isDirectory()) {
                fileList[i].icon = R.drawable.directory_icon;
                Log.d("DIRECTORY", fileList[i].file);
            } else {
                Log.d("FILE", fileList[i].file);
            }
        }

        if (!firstLvl) {
            Item temp[] = new Item[fileList.length + 1];
            for (int i = 0; i < fileList.length; i++) {
                temp[i + 1] = fileList[i];
            }
            temp[0] = new Item("Up", R.drawable.directory_up);
            fileList = temp;
        }
    } else {
        Log.e(TAG, "path does not exist");
    }

    adapter = new ArrayAdapter<Item>(this,
            android.R.layout.select_dialog_item, android.R.id.text1,
            fileList) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // creates view
            View view = super.getView(position, convertView, parent);
            TextView textView = (TextView) view
                    .findViewById(android.R.id.text1);

            // put the image on the text view
            textView.setCompoundDrawablesWithIntrinsicBounds(
                    fileList[position].icon, 0, 0, 0);

            // add margin between image and text (support various screen
            // densities)
            int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
            textView.setCompoundDrawablePadding(dp5);

            return view;
        }
    };

}

private class Item {
    public String file;
    public int icon;

    public Item(String file, Integer icon) {
        this.file = file;
        this.icon = icon;
    }

    @Override
    public String toString() {
        return file;
    }
}

@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    AlertDialog.Builder builder = new Builder(this);

    if (fileList == null) {
        Log.e(TAG, "No files loaded");
        dialog = builder.create();
        return dialog;
    }

    switch (id) {
    case DIALOG_LOAD_FILE:
        builder.setTitle("Choose your file");
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                chosenFile = fileList[which].file;
                File sel = new File(path + "/" + chosenFile);
                if (sel.isDirectory()) {
                    firstLvl = false;

                    // Adds chosen directory to list
                    str.add(chosenFile);
                    fileList = null;
                    path = new File(sel + "");

                    loadFileList();

                    removeDialog(DIALOG_LOAD_FILE);
                    showDialog(DIALOG_LOAD_FILE);
                    Log.d(TAG, path.getAbsolutePath());



                }

                // Checks if 'up' was clicked
                else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {

                    // present directory removed from list
                    String s = str.remove(str.size() - 1);

                    // path modified to exclude present directory
                    path = new File(path.toString().substring(0,
                            path.toString().lastIndexOf(s)));
                    fileList = null;

                    // if there are no more directories in the list, then
                    // its the first level
                    if (str.isEmpty()) {
                        firstLvl = true;
                    }
                    loadFileList();

                    removeDialog(DIALOG_LOAD_FILE);
                    showDialog(DIALOG_LOAD_FILE);
                    Log.d(TAG, path.getAbsolutePath());

                }

                // File picked
                else {
                    chosenFile = fileList[which].file;
                    File test = new File(path + "/" + chosenFile);

                    sendback(test);

                }
            }
        });
        break;
    }
    dialog = builder.show();
    return dialog;
}

抱歉,有点太长了。但这就是 onCreate() 中的整个文件选择器。 我使用以下代码打开它:

Bundle b = new Bundle();
            b.putInt("tallet", 1);
            Intent i = new Intent(getApplicationContext(), FileExplore.class);
            i.putExtras(b);
            startActivityForResult(i, 0);

代码完美运行。但是当我按“返回”(onBackPressed)时,如果我说完成(),它会给我空白(黑色)屏幕; . 现在我正在使用这段代码:

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();

    Intent backIntent = new Intent(FileExplore.this, AndroidTabLayoutActivity.class);
     startActivity(backIntent); 
} 

这确实有效,但是如果我按一次返回,然后当我再次按返回按钮时,它会给我黑屏。 编辑:它在第二次后按时进入 onBackPressed 代码,而不是第一次。

这是我在 PhotosActivity 中的 onActivityResult 代码(它是一个选项卡布局 - photosactivity 只是其中一个屏幕):

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        //  Bundle b = getIntent().getExtras();

        if (resultCode == -1) 
        {
         Bundle b =  data.getBundleExtra("FiletoPhoto");

                int knappen = b.getInt("number");
            String titlen = b.getString("title");
                        {
                            Listofsounds los = new Listofsounds();
                        String shortname    = los.puttextonit(titlen, knappen);

                    putnameinit(shortname,knappen);
                        }
        }
        else if (resultCode == 0)
        {
            //If I press "back" i've made the resultCode to be 0 in the onBackPressed. What should I do here then?
        }

    }  

我应该怎么做才能只按一次它并返回菜单?

【问题讨论】:

    标签: android android-intent filepicker


    【解决方案1】:

    问题是当你使用这段代码时:

     Intent backIntent = new Intent(FileExplore.this, AndroidTabLayoutActivity.class);
     startActivity(backIntent);
    

    您基本上是在创建并启动一个已经存在的 AndroidTabLayoutActivity 的新活动,因此现在将有两个该活动的副本同时运行。但是,原始活动将期待您调用 startActivityForResult() 的结果。我认为您的问题的解决方案可能是检查您作为 onActivityResult 返回的 resultCode 是否为 RESULT_OK 或您在 FileExplore 的 setResult(...) 中设置的任何成功的 resultCode。

    这真的很奇怪,因为在我的所有应用程序中我都没有覆盖 onBackPressed,但是,我能够完成活动而不会造成任何奇怪的副作用。

    【讨论】:

    • 抱歉回复晚了。我不太明白这一点。所以我应该在 FileExplore 中创建一个 onActivityResult - 在该方法中检查 resultCode 是否等于 0(或什么?)。然后呢?
    • 我把它改成了 dialog.cancel();现在在 onBackPressed() 中。但是还是先黑屏再回到主屏幕。
    • 您是否了解如果您使用 startActivity(backIntent) 您将创建同一活动的两个实例(该活动是 AndroidTabLayoutActivity)?一个已经存在,另一个将由 backIntent 调用 startActivity 创建。无需在 onBackPressed 中调用 dialog.cancel()。当我提到 startActivityForResult 时,我指的是 AndroidTabLayoutActivity 而不是 FileExplore,我假设您在 AndroidTabLayoutActivity 中确实有一个 onActivityResult() 方法,因为您正在使用此代码(在下一条评论中继续)
    • Intent i = new Intent(getApplicationContext()FileExplore.class);i.putExtras(b); startActivityForResult(i, 0);由于您正在调用 startActivityForResult,您应该检查从 FileExplore 返回的结果是否为 RESULT_OK(您必须使用 setResult(RESULT_OK, intenttosendtoAndroiTabLayouActivity) 在 FileExplore 类中手动设置结果;请先阅读 Android 中的 onActivityResult() 方法。基本上 onActivityResult 允许你得到一个结果,你可以检查结果代码是否为 RESULT_OK ,然后才做一些事情。
    • 哦,当然。我确实有 onActivityResult。当我选择一个文件时,这部分工作正常。但不是在 onBackPressed 时。现在最有效的是当我调用 dialog.cancel(); - 它不会创造新的意图并且它“有效”。但它仍然首先给我黑屏 - 然后在第二次点击时它给我我想要的屏幕。 用我的 onActivityResult 代码编辑了我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2019-01-17
    相关资源
    最近更新 更多