并提前感谢您的建议。
MainActivity.java
RecyclerView.Adapter mAdapter;
@Override
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
mAdapter = new MyAdapter(getBaseContext(),TITLES,ICONS,NAME,EMAIL,PROFILE);
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
...}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
String path = "";
mImageCaptureUri = data.getData();
path = getPath(mImageCaptureUri); //from Gallery
if (path == null)
path = mImageCaptureUri.getPath();
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
mImageView.setImageBitmap(bitmap);
}
Myadapter.java
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
...
Context mContext;
Activity mActivity;
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
public static class ViewHolder extends RecyclerView.ViewHolder {...}
MyAdapter(Context context, String Titles[],int Icons[],String Name,String Email, int Profile){
this.mContext = context;
mNavTitles = Titles
mIcons = Icons;
name = Name;
email = Email;
profile = Profile;
}
@Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
if(holder.Holderid ==1) {
holder.textView.setText(mNavTitles[position - 1]);
holder.imageView.setImageResource(mIcons[position -1]);
}
else{
holder.profile.setImageResource(profile);
holder.Name.setText(name);
holder.email.setText(email);
holder.profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mActivity = (Activity)mContext;
Intent imageIntent = new Intent();
imageIntent.setType("image/*");
imageIntent.setAction(imageIntent.ACTION_GET_CONTENT);
mActivity.startActivityForResult(Intent.createChooser(imageIntent, "Select photo"), 2);
}
});
}
}
可以在适配器中调用startActivityForResult
吗?
为什么错误出现在mActivity = (Activity)mContext;
?
p.s。:我试图创建方法
public void startxx(Intent i){
startActivityForResult(i, 2);
}
并在适配器中调用它...但适配器需要statxx static和Activity非静态。
答案 0 :(得分:2)
Context是Activity的基类。你不能在Java中转发对象。这就是为什么你不能执行mActivity = (Activity)mContext;
。
您不能从Adapter类调用startActivityForResult(),因为它是Activity.java类的方法。这是您可以尝试的一种解决方案 - - 声明一个接口。说IObserver.java
public interface IObserver {
// change signature of method as per your need
public abstract void onItemClicked();
}
}
在Adapter类中写一个方法说
public void setListener(IObserver obs){ mObserver = obs; }
在Activity类中实现IObserver接口。您还需要实现onItemClicked()方法。
从onCreate()活动方法,调用adapter.setListener(this);
holder.profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // It will call method from activity class where you can do startActivityForResult() mObserver.onItemClicked(); } });
希望它会有所帮助。