1. 程式人生 > >一分鐘實現Android多張圖片選擇

一分鐘實現Android多張圖片選擇

圖片選擇器, 支援多圖選擇和圖片預覽等功能。

  1. 支援jitpack
  2. 支援選擇多張
  3. 支援選擇圖片數量上限
  4. 支援圖片選擇順序
  5. 支援圖片預覽

多圖選擇.gif

使用步驟

1. 在project的build.gradle新增如下程式碼(如下圖)

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
    }
}

2. 在Module的build.gradle新增依賴

  compile 'com.github.open-android:ImageSelector:0.1.0'

3. 配置如下許可權

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.CAMERA"/>

4.複製如下程式碼到xml佈局

 <Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="selectImg"
    android:text="@string/image_selector_select_image" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

5.複製如下程式碼到java類當中

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_SELECT_IMG = 1;
    private static final int MAX_SELECT_COUNT = 9;
    private TextView mContentTv;

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

    private void initView() {
        mContentTv = (TextView) findViewById(R.id.content);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_SELECT_IMG) {
            showContent(data);
            return;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void showContent(Intent data) {
        List<String> paths = ImageSelector.getImagePaths(data);
        if (paths.isEmpty()) {
            mContentTv.setText(R.string.image_selector_select_none);
            return;
        }

        mContentTv.setText(paths.toString());
    }

    public void selectImg(View v) {
        ImageSelector.show(this, REQUEST_CODE_SELECT_IMG, MAX_SELECT_COUNT);
    }}

歡迎關注微信公眾號