Android GridView 확장
20420 단어 Android위 챗 동태마이크로 블 로그 동태
0.효과 도
1.자원 이미지 준비
그림+번호 추가
그림 삭제
2.사용자 가 최대 장 수 를 선택 할 수 있 도록 제한 설정 가능
/**
* , + ,
* 9
*/
private int maxImages = 9;
/**
*
*
* @return
*/
public int getMaxImages() {
return maxImages;
}
/**
*
*
* @param maxImages
*/
public void setMaxImages(int maxImages) {
this.maxImages = maxImages;
}
3.GridView 의 총 수 를 설정 합 니 다.
/**
* GridView 1 +
* +
* @return GridView
*/
@Override
public int getCount() {
int count = datas == null ? 1 : datas.size() + 1;
if (count >= maxImages) {
return datas.size();
} else {
return count;
}
}
4.getView()에서 position 판단+번호 표시
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_published_grida, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
/** + **/
if (datas != null && position < datas.size()) {
final File file = new File(datas.get(position).get("path").toString());
Glide.with(context)
.load(file)
.priority(Priority.HIGH)
.into(viewHolder.ivimage);
viewHolder.btdel.setVisibility(View.VISIBLE);
viewHolder.btdel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (file.exists()) {
file.delete();
}
datas.remove(position);
notifyDataSetChanged();
}
});
} else {
/** + + **/
Glide.with(context)
.load(R.mipmap.image_add)
.priority(Priority.HIGH)
.centerCrop()
.into(viewHolder.ivimage);
viewHolder.ivimage.setScaleType(ImageView.ScaleType.FIT_XY);
viewHolder.btdel.setVisibility(View.GONE);
}
return convertView;
}
5.GridView 의 전체 코드
package cn.bluemobi.dylan.gridviewaddimage;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* com.bm.falvzixun.adapter.GridViewAddImgAdpter
*
* @author yuandl on 2015/12/24.
*
*/
public class GridViewAddImgesAdpter extends BaseAdapter {
private List<Map<String, Object>> datas;
private Context context;
private LayoutInflater inflater;
/**
* , + ,
* 9
*/
private int maxImages = 9;
public GridViewAddImgesAdpter(List<Map<String, Object>> datas, Context context) {
this.datas = datas;
this.context = context;
inflater = LayoutInflater.from(context);
}
/**
*
*
* @return
*/
public int getMaxImages() {
return maxImages;
}
/**
*
*
* @param maxImages
*/
public void setMaxImages(int maxImages) {
this.maxImages = maxImages;
}
/**
* GridView 1 +
* +
* @return GridView
*/
@Override
public int getCount() {
int count = datas == null ? 1 : datas.size() + 1;
if (count >= maxImages) {
return datas.size();
} else {
return count;
}
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
public void notifyDataSetChanged(List<Map<String, Object>> datas) {
this.datas = datas;
this.notifyDataSetChanged();
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_published_grida, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
/** + **/
if (datas != null && position < datas.size()) {
final File file = new File(datas.get(position).get("path").toString());
Glide.with(context)
.load(file)
.priority(Priority.HIGH)
.into(viewHolder.ivimage);
viewHolder.btdel.setVisibility(View.VISIBLE);
viewHolder.btdel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (file.exists()) {
file.delete();
}
datas.remove(position);
notifyDataSetChanged();
}
});
} else {
/** + + **/
Glide.with(context)
.load(R.mipmap.image_add)
.priority(Priority.HIGH)
.centerCrop()
.into(viewHolder.ivimage);
viewHolder.ivimage.setScaleType(ImageView.ScaleType.FIT_XY);
viewHolder.btdel.setVisibility(View.GONE);
}
return convertView;
}
public class ViewHolder {
public final ImageView ivimage;
public final Button btdel;
public final View root;
public ViewHolder(View root) {
ivimage = (ImageView) root.findViewById(R.id.iv_image);
btdel = (Button) root.findViewById(R.id.bt_del);
this.root = root;
}
}
}
6.용법주 레이아웃 파일 activitymain.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:background="#FFFFFF"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="cn.bluemobi.dylan.gridviewaddimage.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" "
android:textColor="#000000" />
<GridView
android:layout_marginTop="10dp"
android:id="@+id/gw"
android:numColumns="5"
android:horizontalSpacing="6dp"
android:columnWidth="60dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
gridview 의 item 레이아웃 파일 itempublished_grida.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="66dp"
android:layout_height="66dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_image"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
<Button
android:id="@+id/bt_del"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:background="@drawable/bt_dynamic_del" />
</RelativeLayout>
</RelativeLayout>
팝 업 사진 과 앨범 에서 선택 한 대화 상자 레이아웃 파일 dialogadd_picture.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5.0dip"
android:layout_marginRight="5.0dip"
android:background="@android:color/transparent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="30px"
android:orientation="vertical">
<TextView
android:id="@+id/tv_camera"
android:layout_width="wrap_content"
android:layout_height="144px"
android:background="@mipmap/btn_top_arc"
android:gravity="center"
android:text=" "
android:textColor="#666666"
android:textSize="48px" />
<ImageView
android:layout_width="1022px"
android:layout_height="4px"
android:background="#666666" />
<TextView
android:id="@+id/tv_gallery"
android:layout_width="wrap_content"
android:layout_height="144px"
android:gravity="center"
android:background="@mipmap/btn_bottom_arc"
android:text=" "
android:textColor="#666666"
android:textSize="48px" />
</LinearLayout>
<TextView
android:id="@+id/tv_cancel"
android:layout_width="wrap_content"
android:layout_height="144px"
android:layout_marginTop="20px"
android:layout_marginLeft="30px"
android:layout_marginRight="30px"
android:layout_gravity="center_horizontal"
android:background="@mipmap/btn_top_arc"
android:gravity="center"
android:text=" "
android:textColor="#666666"
android:textSize="48px" />
</LinearLayout>
MainActivity
package cn.bluemobi.dylan.gridviewaddimage;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import net.bither.util.NativeUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private GridView gw;
private List<Map<String, Object>> datas;
private GridViewAddImgesAdpter gridViewAddImgesAdpter;
private Dialog dialog;
private final int PHOTO_REQUEST_CAREMA = 1;//
private final int PHOTO_REQUEST_GALLERY = 2;// private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
private File tempFile;
private final String IMAGE_DIR = Environment.getExternalStorageDirectory() + "/gridview/";
/* */
private final String PHOTO_FILE_NAME = "temp_photo.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gw = (GridView) findViewById(R.id.gw);
datas = new ArrayList<>();
gridViewAddImgesAdpter = new GridViewAddImgesAdpter(datas, this);
gw.setAdapter(gridViewAddImgesAdpter);
gw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
showdialog();
}
});
}
/**
*
*/
public void showdialog() {
View localView = LayoutInflater.from(this).inflate(
R.layout.dialog_add_picture, null);
TextView tv_camera = (TextView) localView.findViewById(R.id.tv_camera);
TextView tv_gallery = (TextView) localView.findViewById(R.id.tv_gallery);
TextView tv_cancel = (TextView) localView.findViewById(R.id.tv_cancel);
dialog = new Dialog(this, R.style.custom_dialog);
dialog.setContentView(localView);
dialog.getWindow().setGravity(Gravity.BOTTOM);
//
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.width = display.getWidth(); //
dialog.getWindow().setAttributes(lp);
dialog.show();
tv_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
tv_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
//
camera();
}
});
tv_gallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
//
gallery();
}
});
}
/**
*
*/
public void camera() {
// ,
if (hasSdcard()) {
File dir = new File(IMAGE_DIR);
if (!dir.exists()) {
dir.mkdir();
}
tempFile = new File(dir,
System.currentTimeMillis() + "_" + PHOTO_FILE_NAME);
// uri
Uri uri = Uri.fromFile(tempFile);
Intent intent = new Intent();
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addCategory(intent.CATEGORY_DEFAULT);
// Activity, PHOTO_REQUEST_CAREMA
startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
} else {
Toast.makeText(this, " , !", Toast.LENGTH_SHORT).show();
}
}
/**
* sdcard
*/
public boolean hasSdcard() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
* 2
*/
public void gallery() {
Intent intent = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PHOTO_REQUEST_GALLERY) {
//
if (data != null) {
//
Uri uri = data.getData();
String[] proj = {MediaStore.Images.Media.DATA};
// android , Android
Cursor cursor = managedQuery(uri, proj, null, null, null);
//
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// , ,
cursor.moveToFirst();
//
String path = cursor.getString(column_index);
uploadImage(path);
}
} else if (requestCode == PHOTO_REQUEST_CAREMA) {
if (resultCode != RESULT_CANCELED) {
//
if (hasSdcard()) {
if (tempFile != null) {
uploadImage(tempFile.getPath());
} else {
Toast.makeText(this, " !", Toast.LENGTH_SHORT).show();
}
Log.i("images", " path=" + tempFile.getPath());
} else {
Toast.makeText(this, " , !", Toast.LENGTH_SHORT).show();
}
}
}
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0xAAAAAAAA) {
photoPath(msg.obj.toString());
}
}
};
/**
*
*
* @param path
*/
private void uploadImage(final String path) {
new Thread() {
@Override
public void run() {
if (new File(path).exists()) {
Log.d("images", " " + path);
} else {
Log.d("images", " " + path);
}
File dir = new File(IMAGE_DIR);
if (!dir.exists()) {
dir.mkdir();
}
final File file = new File(dir + "/temp_photo" + System.currentTimeMillis() + ".jpg");
NativeUtil.compressBitmap(path, file.getAbsolutePath(), 50);
if (file.exists()) {
Log.d("images", " " + file.getAbsolutePath());
} else {
Log.d("images", " " + file.getAbsolutePath());
}
Message message = new Message();
message.what = 0xAAAAAAAA;
message.obj = file.getAbsolutePath();
handler.sendMessage(message);
}
}.start();
}
public void photoPath(String path) {
Map<String,Object> map=new HashMap<>();
map.put("path",path);
datas.add(map);
gridViewAddImgesAdpter.notifyDataSetChanged();
}
}
7.GitHub 소스 코드:GridViewAddImage이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.