如何将回调从Adapter返回到Fragment类

时间:2016-09-27 02:17:42

标签: android android-fragments

我有一个网格视图,其中包含片段中显示的图像和相关复选框。 Fragment类包括从Gallery或相机捕获图像的方法。如何使用已单击的项目引用从Adapter转移到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;
}

}

2 个答案:

答案 0 :(得分:3)

你可以这样做:

ImageGridAdapter

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

}

片段

AfterReadHandler<T>

答案 1 :(得分:0)

首先从适配器外部传递列表。

//object which store your item
public class SampleListItem{
    public String web;
    public int image;
    public boolean selected = false;   //--> use this flag

}

//适配器

public class SampleListItemAdapter extends BaseAdapter {
    private Context context;
    private List<SampleListItem> sampleList;


    public SampleListItemAdapter (Context context, List<SampleListItem> sampleList) {
        this.context = context;
        this.sampleList= sampleList;
    }

    @Override
    public int getCount() {
        return sampleList.size();
    }

    @Override
    public Object getItem(int position) {
        return sampleList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.adapter, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        SampleListItem listItem= sampleList.get(position);
        viewHolder.tv_web.setText(listItem.getName());


        int image = listItem.getImage();
        if (image != -1) {
            viewHolder.iv_img.setImageResource(image);
        }

        return convertView;
    }

    public void updateList(List<SampleListItem> sampleList) {
        this.sampleList = sampleList;
        notifyDataSetChanged();
    }

    static class ViewHolder {
        @Bind(R.id.iv_img)
        ImageView iv_img;
        @Bind(R.id.tv_web)
        TextView tv_web;


        public ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}

//选择项目时。使选中的标志=真。其他人做错了。

SampleListItemAdapter adapter = new SampleListItemAdapter (activity, sampleList);
//eg. you may change the any element in samepleList selected flag into true and //call updateList 
        if (adapter != null) {
            adapter.updateList(sampleList);
        }

//然后在列表中进行筛选,获取选择并处理图像的那个。 //我改变了我的代码来提供这个样本,如果是这样的话,可能是我错过了一些名字。