避免app按下后退按钮退出

时间:2018-02-14 04:24:59

标签: java android android-activity android-recyclerview onbackpressed

我在文件管理器应用程序中有一个主要活动和一个适配器。所以当我在应用程序中打开一个文件夹,然后打开一个子文件夹,然后按回按钮,它回到主屏幕/主屏幕
我想在返回时返回子文件夹屏幕,然后按回到文件夹屏幕,然后按回到主屏幕..

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

我怎样才能做到这一点?

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 个答案:

答案 0 :(得分:0)

您可以尝试创建堆栈条目以满足您的要求,请按照步骤

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

       }