안 드 로 이 드 는 그림 을 선택 하 는 예제 코드 를 작성 합 니 다.
다음은 인 스 턴 스 효과 그림 입 니 다.
MainActivity 클래스
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, ImageAdapter.OnImageCheckListener, View.OnClickListener {
private static final int CAMERA_CODE = 12;
List<File> fileList = new ArrayList<>();
ImageAdapter adapter;
GridView gvImage;
TextView tvFinish;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
// ,
loadData();
}
private void initView() {
gvImage = (GridView) findViewById(R.id.gv_image);
tvFinish = (TextView) findViewById(R.id.tv_finish);
adapter = new ImageAdapter(this, fileList);
adapter.setOnImageCheckListener(this);
gvImage.setAdapter(adapter);
gvImage.setOnItemClickListener(this);
gvImage.setOnItemLongClickListener(this);
tvFinish.setOnClickListener(this);
}
private ProgressDialog showProgressDialog() {
//
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle(" ");
dialog.setMessage(" , 。。。");
dialog.show();
return dialog;
}
private void loadData() {
final ProgressDialog dialog = showProgressDialog();
//
new Thread() {
@Override
public void run() {
super.run();
//
// sd
getFile(Environment.getExternalStorageDirectory());
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
adapter.notifyDataSetChanged();
}
});
}
}.start();
}
public void getFile(File dir) {
//1.
File[] files = dir.listFiles();
if (files == null)
return;
// for
for (File file : files) {
if (file.isDirectory())
getFile(file);
else {
//
if (file.getName().endsWith(".png") || file.getName().endsWith(".jpg")) {
fileList.add(file);
}
}
}
}
File cameraFile;
//
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
//getAbsolutePath "/"
cameraFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/" + System.currentTimeMillis() + ".png");
//
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
startActivityForResult(intent, CAMERA_CODE);
} else {
//
File file = fileList.get(position - 1);
//
Intent intent = new Intent(this, ShowBigImage.class);
intent.putExtra("file", file);
startActivity(intent);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("TAG", resultCode + "---------------------");
if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
Log.e("TAG", (cameraFile.exists()) + "");
fileList.add(0, cameraFile);
adapter.notifyDataSetChanged();
}
}
//
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0)
return false;
else {
adapter.open(position);
}
return true;
}
@Override
public void onImageCheck(boolean b) {
//b
tvFinish.setEnabled(b);
}
@Override
public void onClick(View v) {
//
// ,ArrayList ,List
ArrayList<File> resultList = new ArrayList<>();
// true file
SparseBooleanArray booleanArray = adapter.getBooleanArray();
for (int i = 0; i < booleanArray.size(); i++) {
boolean isCheck = booleanArray.get(booleanArray.keyAt(i));
if (isCheck) {
int position = booleanArray.keyAt(i);
resultList.add(fileList.get(position - 1));
}
}
Intent intent = new Intent();
intent.putExtra("list", resultList);
//
setResult(RESULT_OK, intent);
finish();
}
}
이미지 어댑터 클래스
public class ImageAdapter extends ListItemAdapter<File> {
private boolean select = false;
public void open(int posisiont) {
select = true;
booleanArray.put(posisiont, true);
if (onImageCheckListener != null)
onImageCheckListener.onImageCheck(true);
this.notifyDataSetChanged();
}
public void close() {
select = false;
booleanArray.clear();
notifyDataSetChanged();
}
//position
//HashMap<Integer, Boolean> map = new HashMap<>();
private SparseBooleanArray booleanArray = new SparseBooleanArray();
public SparseBooleanArray getBooleanArray() {
return booleanArray;
}
public ImageAdapter(Context context, List<File> list) {
super(context, list);
}
@Override
public int getCount() {
//
return super.getCount() + 1;
}
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
// ImageView iv = new ImageView(mContext);
// iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
// iv.setBackgroundColor(Color.argb(0xFF, 0x07, 0x05, 0x18));
// int width = mContext.getResources().getDisplayMetrics().widthPixels / 3 - 2;
// GridView.LayoutParams params = new GridView.LayoutParams(width, width);
// iv.setPadding(2, 2, 2, 2);
// iv.setLayoutParams(params);
// convertView = iv;
// }
// ImageView iv = (ImageView) convertView;
// if (position == 0) {
// //
// iv.setImageResource(R.mipmap.camera);
// } else {
// iv.setImageURI(Uri.fromFile(getItem(position - 1)));
// }
// return convertView;
// }
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(mContext, R.layout.item_image, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (position == 0) {
holder.image.setImageResource(R.mipmap.camera);
holder.checkBox.setVisibility(View.GONE);
} else {
holder.image.setImageURI(Uri.fromFile(getItem(position - 1)));
if (select) {
holder.checkBox.setVisibility(View.VISIBLE);
//
//null
Boolean b = booleanArray.get(position);
if (b == null || b == false) {
holder.checkBox.setChecked(false);
} else {
holder.checkBox.setChecked(true);
}
//item
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Boolean b = booleanArray.get(position);
if (b == null || b == false)
b = true;
else
b = false;
booleanArray.put(position, b);
// boolean, true
for (int i = 0; i < booleanArray.size(); i++) { //4-true 0==false
// key -- > 3 4
// 0 1 2 3 4 5
boolean isChecked = booleanArray.get(booleanArray.keyAt(i));
Log.e("TAG", "----" + isChecked);
Log.e("TAG", booleanArray.toString());
if (isChecked) {
//
if (onImageCheckListener != null)
onImageCheckListener.onImageCheck(true);
return;
}
}
if (onImageCheckListener != null)
onImageCheckListener.onImageCheck(false);
//
//
close();
}
});
} else {
holder.checkBox.setVisibility(View.GONE);
}
// onCheck
// holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// @Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// booleanArray.put(position, isChecked);
// }
// });
}
return convertView;
}
// 。
//
//
public interface OnImageCheckListener {
public void onImageCheck(boolean b);
}
private OnImageCheckListener onImageCheckListener;
//alt+insert
public void setOnImageCheckListener(OnImageCheckListener onImageCheckListener) {
this.onImageCheckListener = onImageCheckListener;
}
class ViewHolder {
ImageView image;
CheckBox checkBox;
public ViewHolder(View convertView) {
image = (ImageView) convertView.findViewById(R.id.iv_image);
int width = mContext.getResources().getDisplayMetrics().widthPixels / 3 - 2;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, width);
image.setLayoutParams(params);
checkBox = (CheckBox) convertView.findViewById(R.id.cb_check);
}
}
}
ListItemAdapter 클래스
// extends
//
public abstract class ListItemAdapter<T> extends BaseAdapter {
protected Context mContext;
protected List<T> mList;
// ,
//List<File> List<String>
public ListItemAdapter(Context context, List<T> list) {
mContext = context;
mList = list;
}
// List
public void setList(List<T> list) {
this.mList = list;
notifyDataSetChanged();
}
@Override
public int getCount() {
return mList == null ? 0 : mList.size();
}
@Override
public T getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
ShowBigImage 클래스
public class ShowBigImage extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView iv = new ImageView(this);
File file = (File) getIntent().getSerializableExtra("file");
iv.setImageURI(Uri.fromFile(file));
setContentView(iv);
}
}
main_xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.imageselector.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/colorPrimary">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text=" "
android:textColor="@android:color/white"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_finish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:enabled="false"
android:text=" "
android:textColor="@color/textenable" />
</RelativeLayout>
<GridView
android:id="@+id/gv_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="2dp"
android:numColumns="3"
android:verticalSpacing="2dp" />
</LinearLayout>
item_image.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#03030a">
<ImageView
android:id="@+id/iv_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:scaleType="centerCrop"
android:src="@mipmap/camera" />
<CheckBox
android:id="@+id/cb_check"
android:button="@null"
android:layout_width="20dp"
android:layout_height="20dp"
android:background="@drawable/cb_selector"
android:layout_alignParentRight="true"
android:layout_margin="10dp"
/>
</RelativeLayout>
res 아래 color 폴 더 의 textenable.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@android:color/white" android:state_enabled="true" />
<item android:color="@android:color/darker_gray" android:state_enabled="false" />
</selector>
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.