读取SD卡图片,并自动轮播

1、加权限

    <!-- 授予读取外部存储设备的的访问权限 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <!-- 授予写入外部存储设备的的访问权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


2、简单的布局

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.dyw.imagehandler.MainActivity">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image1"
        android:scaleType="fitCenter"/>

</android.support.constraint.ConstraintLayout>


3、Java代码

public class MainActivity extends AppCompatActivity {
    ImageView image1;
    ArrayList<String> fileNames = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fileNames.clear();
        //通过ContentResolver查询所有图片信息
        Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,null,null,null,null);
        while (cursor.moveToNext())
        {
            byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            //将图片保存路径添加到fileNames集合中
            fileNames.add(new String(data,0,data.length-1));
            Log.d("---fileNames---",fileNames+"");
        }
        final int[] currentImg = {2};
        image1 =(ImageView) findViewById(R.id.image1);
        final Handler myhandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg.what==1)
                {
                      image1.setImageBitmap(BitmapFactory.decodeFile(fileNames.get(++currentImg[0]%fileNames.size())));
                }
            }
        };
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                myhandler.sendEmptyMessage(1);
            }
        },0,1500);
    }
}

请多指教!!

关注我的技术公众号,每个工作日都有优质技术文章推送。
微信扫一扫下方二维码即可关注:

猜你喜欢

转载自blog.csdn.net/qq_28190653/article/details/73302523