java - 避免按后退按钮退出应用程序

标签 java android android-activity android-recyclerview onbackpressed

我在文件管理器应用程序中有一个主要 Activity 和一个适配器。因此,当我在应用程序中打开一个文件夹,然后打开一个子文件夹,然后按后退按钮时,它会返回到主屏幕/主屏幕。
我想按“返回”返回子文件夹屏幕,然后按“返回”返回文件夹屏幕,然后按“返回”返回主屏幕。

但是现在,当我按后退按钮时,我会直接返回主屏幕。

我怎样才能实现这个目标?

InternalStorage.java:

public class InternalStorage extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
    MyRecyclerViewAdapter adapter;
    private ArrayList<String> myList, myList2,;
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    public static boolean selectallflag = false;
    RecyclerView recyclerView;
    private static final String TAG = "com.example.dell_1.myapp3.InternalMemory";
    File f = new File(path);//converted string object to file//getting the list of files in string array

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_internal_storage);

        method1(f);
        method2(f);

        // set up the RecyclerView
       setAdapter();

    }

    @Override
    public void onItemClick(View view, int position) {
        String string1 = adapter.getItem(position);
        final File directory = new File(string1);
        if (directory.isDirectory()) {
            method1(directory);
            method2(directory);
           setAdapter():
        } else if (string1.endsWith(".mp3")) {
            Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
            viewIntent1.setDataAndType(Uri.fromFile(directory), "audio/mpeg");
            startActivity(Intent.createChooser(viewIntent1, null));
        } else if (string1.endsWith(".zip")) {
            Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
            viewIntent1.setDataAndType(Uri.fromFile(directory), "application/zip");
            startActivity(Intent.createChooser(viewIntent1, null));
        } else if (string1.endsWith(".mp4")) {
            Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
            viewIntent1.setDataAndType(Uri.fromFile(directory), "video/mp4");
            startActivity(Intent.createChooser(viewIntent1, null));
        } else if (string1.endsWith(".jpeg")) {
            Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
            viewIntent1.setDataAndType(Uri.fromFile(directory), "image/*");
            startActivity(Intent.createChooser(viewIntent1, null));
        } else if (string1.endsWith(".png")) {
            Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
            viewIntent1.setDataAndType(Uri.fromFile(directory), "image/*");
            startActivity(Intent.createChooser(viewIntent1, null));
        } else if (string1.endsWith(".pdf")) {
            Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
            viewIntent1.setDataAndType(Uri.fromFile(directory), "application/pdf");
            startActivity(Intent.createChooser(viewIntent1, null));
        } else if (string1.endsWith(".apk")) {
            Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
            viewIntent1.setDataAndType(Uri.fromFile(directory), "application/vnd.android.package-archive");
            startActivity(Intent.createChooser(viewIntent1, null));
        } else if (string1.endsWith(".txt")) {
            Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
            viewIntent1.setDataAndType(Uri.fromFile(directory), "text/*");
            startActivity(Intent.createChooser(viewIntent1, null));
        } else Toast.makeText(this, "unsupported format", Toast.LENGTH_SHORT)
                .show();
    }


    public ArrayList<String> method1(File f) {
        File list2[] = f.listFiles();
        myList = new ArrayList<>();
        if (list2 != null) {
            for (int i = 0; i < list2.length; i++) {
                myList.add(list2[i].getName());
            }
        } else Toast.makeText(this, "the folder is empty", Toast.LENGTH_SHORT)
                .show();
        return myList;
    }

    public ArrayList<String> method2(File f) {
        File list2[] = f.listFiles();
        myList2 = new ArrayList<>();
        if (list2 != null) {
            for (int i = 0; i < list2.length; i++) {
                myList2.add(list2[i].getPath());
            }
        } else Toast.makeText(this, "the folder is empty", Toast.LENGTH_SHORT)
                .show();
        return myList2;
    }


    @Override
    public void onBackPressed() {
        selectallflag =false;
        super.onBackPressed();
    }

 private void setAdapter(){
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvNumbers);
        int numberOfColumns = 4;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, myList, myList2);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

}

MyRecyclerViewAdapter.java:

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private ArrayList<String> mData;
    private ArrayList<String> mData2;
    private LayoutInflater mInflater;
    private int selected_position ;
    private ItemClickListener mClickListener;
    private ArrayList<String> mSelected = new ArrayList<>();
    ArrayList<Uri> files = new ArrayList<>();
    private static final String TAG = "com.example.dell_1.myapp3.InternalMemory";
    private Context context;

    // data is passed into the constructor
    public MyRecyclerViewAdapter(Context context, ArrayList<String> data, ArrayList<String> data2) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
        this.mData2 = data2;
        this.context = context;
    }

    // inflates the cell layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the textview in each cell
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData.get(position);
        String animal2 = mData2.get(position);
        int THUMBSIZE = 150;
        Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(animal2),
                THUMBSIZE, THUMBSIZE);
        Bitmap thumb = ThumbnailUtils.createVideoThumbnail(animal2, MediaStore.Video.Thumbnails.MINI_KIND);
        holder.myTextView.setText(animal + "");
            if(animal!= null && animal.endsWith(".mp3")){
                holder.myImage.setImageResource(R.drawable.song);
            }
        else if(animal!= null && animal.endsWith(".pdf")){
            holder.myImage.setImageResource(R.drawable.pdficon2);
        }
        else
            if(animal!= null && animal.endsWith(".jpeg") && BitmapFactory.decodeFile(animal2)!=null ){
                holder.myImage.setImageBitmap(ThumbImage);
            }
            else
            if(animal!= null && animal.endsWith(".png") && BitmapFactory.decodeFile(animal2)!=null ){
                holder.myImage.setImageBitmap(ThumbImage);
            }
            else
            if(animal!= null && animal.endsWith(".mp4")){
                holder.myImage.setImageBitmap(thumb);
            }
            else
            if(animal!= null && animal.endsWith(".zip")){
                holder.myImage.setImageResource(R.drawable.zip);
            }
            else
            if(animal!= null && animal.endsWith(".aac")){
                holder.myImage.setImageResource(R.drawable.song);
            }
            else
            if(animal!= null && animal.endsWith(".txt")){
                holder.myImage.setImageResource(R.drawable.text);
            }
           else if(animal!= null && animal.endsWith(".apk")){
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageArchiveInfo(animal2, PackageManager.GET_ACTIVITIES);
            if(packageInfo != null) {
                ApplicationInfo appInfo = packageInfo.applicationInfo;
                    appInfo.sourceDir = animal2;
                    appInfo.publicSourceDir = animal2;
                Drawable icon = appInfo.loadIcon(context.getPackageManager());
                Bitmap bmpIcon = ((BitmapDrawable) icon).getBitmap();
                holder.myImage.setImageBitmap(bmpIcon);
            }

        }
            else {
                holder.myImage.setImageResource(R.drawable.folder);
            }

        if(selectallflag){
            holder.itemView.setBackgroundColor(Color.MAGENTA);
            }
        }


    // total number of cells
    @Override
    public int getItemCount() {
        return mData2.size();
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
        TextView myTextView;
        ImageButton myImage;
        ViewHolder(View itemView) {
            super(itemView);
            myImage = (ImageButton) itemView.findViewById(R.id.buttonimage);
            myTextView = (TextView) itemView.findViewById(R.id.info_text);
            myImage.setOnClickListener(this);
            myImage.setOnLongClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }

    // convenience method for getting data at click position
    public String getItem(int id) {
        return mData2.get(id);
    }

    // allows clicks events to be caught
    public void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
        boolean onLongClick(View view,int position);
    }

最佳答案

您可以尝试创建一个堆栈条目来实现您的要求,请按照以下步骤操作

1.创建列表/堆栈

 Stack<String> stack = new Stack<String>();

2.每当移动到子目录时添加一个条目

   stack.push("nameofthescreen");

3.在 onBackPress() 方法上 检查堆栈中的条目

   if(stack.size()>0)
   {
      String screenName=stack.pop();
       //replace the screens you want as per the string you gave
   }
   else{

           //No entries in the stack you can move to main screen by
          super.onBackPress();
           //or write custom code as you required

       }

关于java - 避免按后退按钮退出应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48779652/

相关文章:

java - jOOQ 是否支持 PostgreSQL 数组函数和运算符?

java - 通过故障转移使长时间运行的任务仅在集群的一台机器上运行?

Android GraphicBufferAlloc::createGraphicBuffer(w=1232, h=800) 失败(内存不足)

java - 重新启动 Activity 后的 NPE

android - 多个 Activity 上的 AsyncTask?

java - 如何打印字符串中第一个重复出现的字符?

java - 如何判断 XML 文档是否针对 DTD 或 XSD 进行验证?

java - 为什么 for 循环不适用于平台 4.2 (API 17)?

android - ActionBarSherlock + maven + eclipse : dependency not found in workspace

c# - Xamarin 安卓 C# : How to pass data back from activity without new intent