gpt4 book ai didi

android - 如何从 Adapter 返回回调到 Fragment 类

转载 作者:搜寻专家 更新时间:2023-11-01 07:48:07 25 4
gpt4 key购买 nike

我有一个 GridView ,在 fragment 中显示了图像和关联的复选框。 Fragment 类包括从 Gallery 或相机捕获图像的方法。如何使用已单击的项目引用引入从 Adapter 到 Fragment 类的回调,以便可以从 Fragment 类执行捕获/加载图像?

必须加载从相机或图库中捕获的图像的网格的 fragment 类:

public class SellMainFrag extends Fragment{

private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView ivImage;
private String userChoosenTask;

public SellMainFrag() {
// Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.sell_main, container, false);

int iconSize=getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);

ImageGridAdapter adapter = new ImageGridAdapter(view.getContext(), iconSize);
GridView gridview = (GridView) view.findViewById(R.id.gridView1);
gridview.setAdapter(adapter);

return view;
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
}
break;
}
}

private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };

AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(getContext());

if (items[item].equals("Take Photo")) {
userChoosenTask ="Take Photo";
if(result)
cameraIntent();

} else if (items[item].equals("Choose from Library")) {
userChoosenTask ="Choose from Library";
if(result)
galleryIntent();

} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}

private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}

private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}

private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");

FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

ivImage.setImageBitmap(thumbnail);
}

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {

Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}

ivImage.setImageBitmap(bm);
}

}

包含用于捕获点击的监听器的适配器类:

public class ImageGridAdapter extends BaseAdapter{
private Context mContext;
private int mIconSize;
private static LayoutInflater inflater=null;

private String[] web = {
"Doctors","Movies","Dentists","Restaurants","Car"} ;

private int[] imageId = {
R.mipmap.doctors,
R.mipmap.dentists,
R.mipmap.restaurants,
R.mipmap.carmechanic,
R.mipmap.ic_launcher
};

public ImageGridAdapter(Context mContext, int mIconSize) {
super();
this.mContext = mContext;
this.mIconSize = mIconSize;
inflater = ( LayoutInflater )mContext.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return imageId.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}

public class Holder
{
CheckBox ck;
ImageView img;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

Holder holder=new Holder();
View rowView;

rowView = inflater.inflate(R.layout.sell_main_images, null);
holder.ck=(CheckBox) rowView.findViewById(R.id.chk1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);

holder.ck.isChecked();
holder.img.setImageResource(imageId[position]);

rowView.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// How do I introduce a callback to Fragment class with the item reference that has been clicked so that capture/loading images can be performed from the Fragment class?

}
});

return rowView;
}

}

最佳答案

你可以这样做:

图像网格适配器

public class ImageGridAdapter extends BaseAdapter{
private Context mContext;
private int mIconSize;
private static LayoutInflater inflater=null;
AdapterCallback callback;

public interface AdapterCallback{
void onItemClicked(int position);
}

private String[] web = {
"Doctors","Movies","Dentists","Restaurants","Car"} ;

private int[] imageId = {
R.mipmap.doctors,
R.mipmap.dentists,
R.mipmap.restaurants,
R.mipmap.carmechanic,
R.mipmap.ic_launcher
};

public ImageGridAdapter(Context mContext, int mIconSize, AdapterCallback callback) {
super();
this.callback = callback;
this.mContext = mContext;
this.mIconSize = mIconSize;
inflater = ( LayoutInflater )mContext.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return imageId.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}

public class Holder
{
CheckBox ck;
ImageView img;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

Holder holder=new Holder();
View rowView;

rowView = inflater.inflate(R.layout.sell_main_images, null);
holder.ck=(CheckBox) rowView.findViewById(R.id.chk1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);

holder.ck.isChecked();
holder.img.setImageResource(imageId[position]);

rowView.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// How do I introduce a callback to Fragment class with the item reference that has been clicked so that capture/loading images can be performed from the Fragment class?
if(callback != null) {
callback.onItemClicked(position);
}

}
});

return rowView;
}

}

fragment

public class SellMainFrag extends Fragment implements AdapterCallback{

private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView ivImage;
private String userChoosenTask;

public SellMainFrag() {
// Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.sell_main, container, false);

int iconSize=getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);

ImageGridAdapter adapter = new ImageGridAdapter(view.getContext(), iconSize, SellMainFrag.this);
GridView gridview = (GridView) view.findViewById(R.id.gridView1);
gridview.setAdapter(adapter);

return view;
}

@Override
public void onItemClicked(int position){
// call back here
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
}
break;
}
}

private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };

AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(getContext());

if (items[item].equals("Take Photo")) {
userChoosenTask ="Take Photo";
if(result)
cameraIntent();

} else if (items[item].equals("Choose from Library")) {
userChoosenTask ="Choose from Library";
if(result)
galleryIntent();

} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}

private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}

private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}

private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");

FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

ivImage.setImageBitmap(thumbnail);
}

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {

Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}

ivImage.setImageBitmap(bm);
}

}

关于android - 如何从 Adapter 返回回调到 Fragment 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39715025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com