Android - 从filepicker /浏览屏幕返回菜单

时间:2012-08-23 15:23:35

标签: android android-intent filepicker

我在网上找到了这个文件选择器,开发人员说,如果他们愿意,人们可以使用。 因为我认为代码很容易理解 - 我决定使用它并为我的应用程序稍微改变一下。 所有功劳都归功于原始开发者(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代码(它是一个tablayout - 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?
        }

    }  

我应该怎么做才能按一下然后返回菜单?

1 个答案:

答案 0 :(得分:0)

问题是当您使用此代码时:

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

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

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