Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

android - How to return a callback from Adapter to Fragment class

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

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

YOu can do like that:

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

}

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...