我的目标是能够点击“上传图片”并将其显示在网格视图上,类似于个人资料上的Instagram Feed(不是滚动Feed,网格Feed)。老实说,我很失落,只是尝试了我在网站上找到的不同方法,但没有真正有效。
MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int RESULT_LOAD_IMAGE = 1;
private ArrayList<Image> items = new ArrayList<Image>();
ImageView uploadedImage;
Button bUploadImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bUploadImage = (Button)findViewById(R.id.bUploadImage);
bUploadImage.setOnClickListener(this);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this,R.id.bUploadImage,items));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(MainActivity.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bUploadImage:
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null){
Uri selectedImage = data.getData();
uploadedImage.setImageURI(selectedImage);
Image i = new Image();
i.setURI(selectedImage);
items.add(i);
}
}
}
ImageAdapter:
public class ImageAdapter extends ArrayAdapter<Image> {
private Context mContext;
private ArrayList<Image> items;
public ImageAdapter(Context context, int textViewResourceId, ArrayList<Image> items) {
super(context, textViewResourceId, items);
mContext = context;
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
if (position == 0)
imageView.setImageURI(items.get(position).getURI());
return imageView;
}
}
图片类:
public class Image {
private Uri imgURI;
public Uri getURI(){
return imgURI;
}
public void setURI(Uri imgURI){
this.imgURI = imgURI;
}
}
我见过很多在网格上显示图像的方法,但没有使用图库中的图像。在上面的代码中,我尝试将图像的Uri从图库传递到适配器,但我对适配器和它的工作原理感到困惑。我是Android Studio的初学者。任何指导都有帮助,谢谢!
答案 0 :(得分:0)
取代onCreate
中的以下行gridview.setAdapter(new ImageAdapter(this,R.id.bUploadImage,items));
创建类级适配器
private ImageAdapter adapter;
和onCreate()
adapter = new ImageAdapter(this,R.id.bUploadImage,items)
gridview.setAdapter(adapter);
在item.add之后的onActivityResult中调用adapter.notifyDatasetChanged。