如何从Adapter返回到Fragment类的回调 [英] How to return a callback from Adapter to Fragment class

查看:66
本文介绍了如何从Adapter返回到Fragment类的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网格视图,其中在片段中显示了图像和相关的复选框. Fragment类包括从Gallery或相机捕获图像的方法.如何通过单击已单击的项目引用从Adapter到Fragment类引入回调,以便可以从Fragment类执行捕获/加载图像?

I have a grid view with images and associated checkbox displayed in the Fragment. The Fragment class includes methods to capture the images from Gallery or camera. How do I introduce a callback from the Adapter to Fragment class with the item reference that has been clicked so that capture/loading images can be performed from the Fragment class?

必须从摄影机或画廊中捕获图像的网格的片段类:

Fragment class where the grid has to be loaded with the image capture from camera or gallery:

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);
}

}

适配器类,其中包含用于捕获点击的侦听器:

Adapter class which includes listener to capture the click:

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;
}

}

推荐答案

您可以这样做:

ImageGridAdapter

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;
}

}

片段

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);
}

}

这篇关于如何从Adapter返回到Fragment类的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆