Android 9 sd卡文件浏览器以及手势放大缩小图片

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sdbrowser">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.MAINACTIVITY"/>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ImageShowActvity">
            <intent-filter>
                <action android:name="android.intent.action.show.Image"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/path"
        android:hint="当前路劲为:"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="400dp"
        android:layout_height="500dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:id="@+id/recycler"
        />


    <Button
        android:id="@+id/bt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:onClick="myOnclick"
        android:text="返回上一层"
        android:textAllCaps="false" />

</LinearLayout>

item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/imageType"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/filename"
        android:textAllCaps="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

image_show.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/show"
        android:layout_width="400dp"
        android:layout_height="400dp"
        />
    <Button
        android:onClick="imageClick"
        android:id="@+id/back"
        android:text="退出"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

MainActivity.java

package com.example.sdbrowser;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int PERMISSION_READ = 0x123;
    private static final int PERMISSION_WRITE =0x456;
    private RecyclerView recyclerView;
    private TextView path,name;
    private ImageView imageView;
    private Button bt;
    private File[] currentFiles;
    private File currentParent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myRequestPermission();
        initUI();

    }
    private void initUI(){
        bt = findViewById(R.id.bt);
        path = findViewById(R.id.path);

        recyclerView = findViewById(R.id.recycler);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
//        recyclerView.setAdapter(new MyRecyclerViewAdapter());

    }
    private void myRequestPermission(){
        this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MainActivity.PERMISSION_WRITE);
        this.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                            MainActivity.PERMISSION_READ);

    }
    public void setCurrent(File[] files,File currentParent){
        this.currentParent = currentParent;
        currentFiles = files;
    }
    public void inflateRecyclerView(File[] files){
        Log.d(TAG, "inflateRecyclerView: ");
        recyclerView.setAdapter(new MyRecyclerViewAdapter(files,MainActivity.this));
        path.setText(currentParent.getPath());
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if(requestCode == MainActivity.PERMISSION_WRITE){
            Log.d(TAG, "onRequestPermissionsResult: gra "+grantResults.length);
            if((grantResults != null) && (grantResults[0]==PackageManager.PERMISSION_GRANTED)){
                File root = new File(Environment.getExternalStorageDirectory().getPath());
                if(root.exists()){
                    currentParent = root;
                    currentFiles = root.listFiles();
//                    for(int i=0;i<currentFiles.length;i++){
//                        Log.d(TAG, "onRequestPermissionsResult: "+currentFiles[i].getName());
//                    }
                    inflateRecyclerView(currentFiles);
                }

            }
        }
    }

    public void myOnclick(View view){
        int id = view.getId();
        switch (id){
            case R.id.bt:

                try{
                    if(!currentParent.getCanonicalPath().equals(Environment.
                            getExternalStorageDirectory().getPath())){
                        currentParent = currentParent.getParentFile();
                        currentFiles = currentParent.listFiles();
                        inflateRecyclerView(currentFiles);
                    }
                }catch (IOException e){

                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: ");
        inflateRecyclerView(currentFiles);
    }
}

MyRecyclerViewAdapter.java

package com.example.sdbrowser;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ItemViewHolder> {
    private static final String TAG=MyRecyclerViewAdapter.class.getSimpleName();
    private File[] files;
    private Context context;
    private static final String ImageAction = "android.intent.action.show.Image";
    public MyRecyclerViewAdapter(File[] files,Context context){
        this.files = files;
        this.context = context;
    }
    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item,null);
        ItemViewHolder itemViewHolder = new ItemViewHolder(view,context);

        return itemViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
        holder.fileName.setText(files[position].getName());
        if(files[position].isDirectory()){
            holder.imageView.setImageResource(R.drawable.format_folder);
        }else{
            holder.imageView.setImageResource(R.drawable.format_text);
        }
    }

    @Override
    public int getItemCount() {
        return files.length;
    }


    public class ItemViewHolder extends RecyclerView.ViewHolder {
        private static final String TAG = "ItemViewHolder";
        public TextView fileName;
        public ImageView imageView;
        private MainActivity activity;
        public ItemViewHolder(@NonNull View itemView, Context context) {
            super(itemView);
            activity=(MainActivity)context;
            fileName = itemView.findViewById(R.id.filename);
            imageView = itemView.findViewById(R.id.imageType);


            itemView.setOnClickListener(view->{
                int position = getAdapterPosition();
                Log.d(TAG, "ItemViewHolder: "+position);

                if(files[position].isDirectory()){
                    File[] tmp = files[position].listFiles();
                    activity.setCurrent(tmp,files[position]);
                    activity.inflateRecyclerView(tmp);
                }else if (files[position].isFile()){
                    String mFileName = files[position].getName();
                    String extName = mFileName.substring(mFileName.lastIndexOf('.')+1);
                    Log.d(TAG, "ItemViewHolder: extname "+extName);
                    if(extName.equals("jpg")||extName.equals("png")||extName.equals("gif")){
                        Intent intent = new Intent();
                        intent.putExtra("filename",files[position].getAbsolutePath());
                        intent.setAction(ImageAction);
                        activity.startActivityForResult(intent,0x33);
                    }

                    return ;
                }
            });
        }
    }
}

ImageShowActvity.java

package com.example.sdbrowser;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.Nullable;

public class ImageShowActvity extends Activity {
    private static final String TAG = "ImageShowActvity";
    private static final String MainActivityAction = "android.intent.action.MAINACTIVITY";
    private String filename;
    private ImageView imageView;
    private int width ;
    private int height ;
    private GestureDetector detector;
    private Matrix matrix;
    private float currentScale = 1.0f;
    private Bitmap bitmap;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_show);
        Intent intent = getIntent();
        filename = intent.getStringExtra("filename");


        detector = new GestureDetector(this,new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                Log.d(TAG, "onFling: "+width+"heigit "+height+" velocityX "+velocityX);
                float vx = velocityX>4000?4000f:velocityX;
                vx = velocityX<-4000?-4000f:velocityX;
                currentScale += currentScale*vx/4000.0f;
                currentScale = currentScale > 0.01?currentScale:0.01f;
                matrix.reset();
//                matrix.setScale(10,10);
                matrix.setScale(currentScale,currentScale,160f,200f);
//                BitmapDrawable tmp = (BitmapDrawable)imageView.getDrawable();
//                if(!tmp.getBitmap().isRecycled()){
//                    tmp.getBitmap().recycle();
//                }
                Bitmap bitmap1 = Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);
                imageView.setImageBitmap(bitmap1);
                return true;
            }
        });
        matrix = new Matrix();
        imageView = findViewById(R.id.show);
        imageView.setScaleType(ImageView.ScaleType.MATRIX);
        bitmap = BitmapFactory.decodeFile(filename);
        width = bitmap.getWidth();
        height = bitmap.getHeight();
        imageView.setImageBitmap(bitmap);
    }
    public void imageClick(View v){
       int id = v.getId();
       switch (id){
           case R.id.back:
               Intent intent = new Intent();
               intent.setAction(MainActivityAction);
               startActivity(intent);
               break;
       }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return detector.onTouchEvent(event);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值