I created a part in my adapter that is responsible for editing profile picture , I am using a library called android image cropper , which need on activity result to run , but since I am in adapter class, It does not let me use Activity methods. I searched but I could not understand the codes, because most of the use activity and I use fragment. this is my adapter class(only a part of it):
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final LayoutInflater inflater=LayoutInflater.from(context);
View add_view=inflater.inflate(R.layout.dialog_addcontacts,null);
AlertDialog alertDialog=new AlertDialog.Builder(context).create();
alertDialog.setView(add_view);
final TextInputEditText edt_name=add_view.findViewById(R.id.edt_name);
final TextInputEditText edt_phonenumber=add_view.findViewById(R.id.edt_number);
byte[] contactimage=phonebookModel.getImage();
Bitmap bitmap= BitmapFactory.decodeByteArray(contactimage,0,contactimage.length);
final CircleImageView image_profile=add_view.findViewById(R.id.profile_image);
Button btn_add=add_view.findViewById(R.id.btn_add);
btn_add.setText("change");
edt_name.setText(phonebookModel.getName());
edt_phonenumber.setText(phonebookModel.getPhonenumber());
image_profile.setImageBitmap(bitmap);
image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setCropShape(CropImageView.CropShape.OVAL)
.setMaxCropResultSize(2500,2500)
.setAspectRatio(1,1)
.setScaleType(CropImageView.ScaleType.CENTER)
.start(getContext(),ContactsFragment.this);
}
}
});
private byte[] imagetobyte(CircleImageView image){
Bitmap bitmap=((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream);
byte[] bytearray=stream.toByteArray();
return bytearray;
}
and this is my fragment:
public class ContactsFragment extends Fragment {
RecyclerView recyclerView;
FloatingActionButton floatingActionButton;
PhoneBookDB phoneBookDB;
CircleImageView imagebutton;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.contactsfragment,container,false);
phoneBookDB =new PhoneBookDB(getContext());
//recycler-contacts
recyclerView= view.findViewById(R.id.recycler_contacts);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),RecyclerView.VERTICAL,false));
List<PhonebookModel> models=phoneBookDB.getalldata();
Contactsadapter adapter=new Contactsadapter(models,getContext());
recyclerView.setAdapter(adapter);
//add-contacts
floatingActionButton=view.findViewById(R.id.btn_add_contacts);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showdialog();
}
});
return view;
}
public void showdialog() {
final LayoutInflater inflater=LayoutInflater.from(getContext());
View add_view=inflater.inflate(R.layout.dialog_addcontacts,null);
final AlertDialog alertDialog=new AlertDialog.Builder(getContext()).create();
alertDialog.setView(add_view);
final TextInputEditText edt_name=add_view.findViewById(R.id.edt_name);
final TextInputEditText edt_phonenumber=add_view.findViewById(R.id.edt_number);
imagebutton=add_view.findViewById(R.id.profile_image);
imagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setCropShape(CropImageView.CropShape.OVAL)
.setMaxCropResultSize(2500,2500)
.setAspectRatio(1,1)
.setScaleType(CropImageView.ScaleType.CENTER)
.start(getContext(),ContactsFragment.this);
}
});
Button btn_add=add_view.findViewById(R.id.btn_add);
Button btn_cancel=add_view.findViewById(R.id.btn_cancel);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!edt_name.getText().toString().isEmpty()&&!edt_phonenumber.getText().toString().isEmpty()) {
long i= phoneBookDB.insertdata(edt_name.getText().toString(), edt_phonenumber.getText().toString(),imagetobyte(imagebutton));
Toast.makeText(getContext(), i+"", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getContext(), MainActivity.class));
}else {
Toast.makeText(getContext(), "لطفا تمامی فیلد های خواسته شده را پر کنید", Toast.LENGTH_SHORT).show();
}
}
});
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
try {
InputStream inputStream= getActivity().getContentResolver().openInputStream(resultUri);
imagebutton.setImageBitmap(BitmapFactory.decodeStream(inputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private byte[] imagetobyte(CircleImageView image){
Bitmap bitmap=((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream);
byte[] bytearray=stream.toByteArray();
return bytearray;
}
From my understanding so far by reading your question, I assume that you would like to start the library activity using CropImage.activity()... and get the crop result with onActivityResult inside Fragment.
In order to get the crop result with onActivityResult inside Fragment, I assume you need to start the library activity using Fragment#startActivityForResult.
To call Fragment#startActivityForResult when adapter item is clicked, I can think of two ways:
Pass the instance of fragment to the adapter class and start activity from fragment when the item is clicked.
Define and pass a on listener from fragment to adapter to make it possible to handle adapter's on click event
Maybe the issue and the comment below helps:
https://github.com/ArthurHub/Android-Image-Cropper/issues/762#issuecomment-648859151
(Maybe it would be helpful if you could clarify both what you know or do, what you have tried, and what you do not know about so it makes it easier for others to understand your situation and understanding level. For example, you could give us some other codes or logics that you have already tried to let others understand your situation clearer. )
Related
This question already has answers here:
RecyclerView: how to catch the onClick on an ImageView?
(2 answers)
Closed 4 years ago.
What I am trying to accomplish is to create a listener for the ImageView inside the row of RecyclerView.
This code is working already, but this is not the solution that I wanted to have, because you need to double click the ImageView before getting the desired result.
// row click listener
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
ImageView viewContent = (ImageView)view.findViewById(R.id.btnViewContent);
ImageView deleteContent = (ImageView)view.findViewById(R.id.btnDeleteContent);
viewContent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "VIEW CONTENT", Toast.LENGTH_SHORT).show();
}
});
deleteContent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "DELETE CONTENT", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onLongClick(View view, int position) {}
}));
Any idea how to translate this into single click solution? Advice or even a single comment would help me a lot.
This is not the right way as one of our friend suggested onBindViewHolder is caleed again and again during scrolling so it is not the best practice to add listener there.
Best way is to add it on ViewHolder as I suggested. Check my answer above.
Add your imageView click listener in OnBindViewHolder method
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.btnClassAddCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what you want here
}
});
}
Then there is no need to implement recyclerView.addOnItemTouchListener , inside Viewholder just add clicklistener on the view(image) you want below is the example for reference.
` public static class HeaderViewHolder extends RootViewHolder {
#BindView(R.id.cardview)
CardView cardview;
#BindView(R.id.main_container)
LinearLayout main_container;
#BindView(R.id.music_cardview)
CardView music;
#BindView(R.id.shabad_cardview)
CardView shabadvaani;
#BindView(R.id.news_cardview)
CardView news;
#BindView(R.id.donate_cardview)
CardView donate;
#BindView(R.id.bs_cardview)
CardView bs;
#BindView(R.id.bl_cardview)
CardView bl;
#BindView(R.id.bng_cardview)
CardView bng;
#BindView(R.id.more_cardview)
CardView more;
#BindView(R.id.vid_cardview)
CardView vid;
#BindView(R.id.medi_cardview)
CardView medi;
//
// #BindView(R.id.ama_cardview)
// CardView ama;
public HeaderViewHolder(final View itemView,final OnItemClickListener mOnItemClickListener) {
super(itemView);
ButterKnife.bind(this, itemView);
news.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.openDrawer();
}
//Intent i= new Intent(ctx,);
//open drawer code
}
});
shabadvaani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, IndexActivity.class);
ctx.startActivity(i);
}
});
music.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, MainActivity.class);
i.putExtra("slug","audiobhajan");
ctx.startActivity(i);
//open drawer code
}
});
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent i = new Intent(ctx, stayrocks.jambh.vani.auth.MainActivity.class);
// ctx.startActivity(i);
if (mOnItemClickListener != null) {
mOnItemClickListener.openDrawer();
}
//open drawer code
}
});
bs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(ctx, AmaActivity.class);
ctx.startActivity(intent);
}
});
bl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, ItemListActivity.class);
ctx.startActivity(i);
//open drawer code
}
});
bng.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, WallpaperActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
medi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, stayrocks.jambh.vani.activities.jyot.MainActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
vid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, VideoListDemoActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
// ama.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//// String appPackage = "com.my.bishnoi.nextgen";
//// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
//// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Intent intent= new Intent(ctx, AmaActivity.class);
// ctx.startActivity(intent);
// //open drawer code
// }
// });
}
}
`
Add your imageView click listener in OnBindViewHolder method
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what you want here
}
});
}
Hello I'm trying to select an Image in an activity page and that selected image to update in my Fragment page. I've tried what I've learnt previously, but it's not working at all. Below is what I've attempted. I'm still new to android development, so please bear with me.
ProfileSettingsActivity.java:
public class ProfileSettingsActivity extends AppCompatActivity {
ImageView profileImage1;
ImageView profileImage2;
ImageView profileImage3;
ImageView profileImage4;
ImageView profileImage5;
ImageView profileImage6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_settings);
profileImage1 = (ImageView) findViewById(R.id.teamid00);
profileImage2 = (ImageView) findViewById(R.id.teamid01);
profileImage3 = (ImageView) findViewById(R.id.teamid02);
profileImage4 = (ImageView) findViewById(R.id.teamid03);
profileImage5 = (ImageView) findViewById(R.id.teamid04);
profileImage6 = (ImageView) findViewById(R.id.teamid05);
profileImage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
}
public void setProfilePicture(View view) {
//Creating a Return intent to pass to the Main Activity
Intent returnIntent = new Intent();
//Figuring out which image was clicked
ImageView selectedImage = (ImageView) view;
//Adding stuff to the return intent
returnIntent.putExtra("imageID", selectedImage.getId());
setResult(RESULT_OK, returnIntent);
//Finishing Activity and return to main screen!
finish();
}
}
Below is the Fragment that contains the page I start on from and go to the ProfileSettingsActivity page
PeopleFragment.java:
public class PeopleFragment extends Fragment {
ImageButton settingsButton;
PieChart pieChart;
ImageButton profileImage;
private FirebaseAuth mAuth;
TextView fullName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_people2, container,
false);
profileImage = (ImageButton) view.findViewById(R.id.imageButton4);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent settingsClick = new Intent(getActivity(),
ProfileSettingsActivity.class);
getActivity().startActivityForResult(settingsClick,0);
}
});
fullName = (TextView) view.findViewById(R.id.userProfileFullName);
mAuth = FirebaseAuth.getInstance();
return view;
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
/**
* Updates the view according to the authentication status.
* #param user the current FirebaseUser
*/
private void updateUI(FirebaseUser user) {
if (user != null) {
fullName.setText(user.getDisplayName());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_CANCELED) return;
//Getting the Avatar Image we show to our users
ImageView avatarImage =
(ImageView)getView().findViewById(R.id.imageButton4);
//Figuring out the correct image
String drawableName = "profile1";
switch (data.getIntExtra("imageID",R.id.teamid00)) {
case R.id.teamid00:
drawableName = "profile1";
break;
case R.id.teamid01:
drawableName = "profile2";
break;
case R.id.teamid02:
drawableName = "profile3";
break;
case R.id.teamid03:
drawableName = "profile4";
break;
case R.id.teamid04:
drawableName = "profile5";
break;
case R.id.teamid05:
drawableName = "profile6";
break;
default:
drawableName = "profile1";
break;
}
int resID = getResources().getIdentifier(drawableName, "drawable",
getActivity().getPackageName());
avatarImage.setImageResource(resID);
}
}
Currently with what I have above, I can move from the fragment page to the activity page and I can press on the buttons to select the images and then the activity closes for me. But when I'm back on the fragment page, the profile image isn't updated at all, and displays the default one.
Try to use startActivityForResult() instead of getActivity().startActivityForResult(). So, change your Fragment code to:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent settingsClick = new Intent(getActivity(),
ProfileSettingsActivity.class);
startActivityForResult(settingsClick,0);
}
});
...
return view;
}
Note: This is not related to your problem.
You can simplify you activity code to this:
public class ProfileSettingsActivity extends AppCompatActivity {
ImageView profileImage1;
ImageView profileImage2;
ImageView profileImage3;
ImageView profileImage4;
ImageView profileImage5;
ImageView profileImage6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_settings);
profileImage1 = (ImageView) findViewById(R.id.teamid00);
profileImage2 = (ImageView) findViewById(R.id.teamid01);
profileImage3 = (ImageView) findViewById(R.id.teamid02);
profileImage4 = (ImageView) findViewById(R.id.teamid03);
profileImage5 = (ImageView) findViewById(R.id.teamid04);
profileImage6 = (ImageView) findViewById(R.id.teamid05);
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
};
profileImage1.setOnClickListener(clickListener);
profileImage2.setOnClickListener(clickListener);
profileImage3.setOnClickListener(clickListener);
profileImage4.setOnClickListener(clickListener);
profileImage5.setOnClickListener(clickListener);
profileImage6.setOnClickListener(clickListener);
}
public void setProfilePicture(View view) {
//Creating a Return intent to pass to the Main Activity
Intent returnIntent = new Intent();
//Figuring out which image was clicked
ImageView selectedImage = (ImageView) view;
//Adding stuff to the return intent
returnIntent.putExtra("imageID", selectedImage.getId());
setResult(RESULT_OK, returnIntent);
//Finishing Activity and return to main screen!
finish();
}
}
Probably you've got some problems with your onActivityResult method. Check these answers.
Also there is a solution that is going to work:
1. Tag your fragments when you create them:
FragmentTransaction fTrans = getFragmentManager().beginTransaction();
fTrans.add(R.id.main_layout, new PeopleFragment(), "PeopleFragmentTag"));
fTrans.commit();
2. Write method in PeopleFragment, which could setImage:
public void updateProfileImage(int profileImgID){
/* Update your image here */
}
3. Get a fragment by tag and call the method:
public void setProfilePicture(View view) {
/* Your code */
PeopleFragment peopleFragment = (PeopleFragment) getFragmentManager().findFragmentByTag("PeopleFragmentTag");
peopleFragment.updateProfileImage(selectedImage.getId());
}
Hope, I helped you somehow. Good luck!
I created below class but numbers is coming null. The same code is working fine with activity. I have made changes in context of Fragment. What else is creating problem in the code.
public class TestFrag extends Fragment {
private static final String[] phoneProjection = new String[]{ContactsContract.CommonDataKinds.Phone.DATA};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testfrag, container, false);
TextView textView = (TextView) view.findViewById(R.id.clickme);
EditText editText = (EditText) view.findViewById(R.id.contact);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
getActivity().startActivityForResult(intent, 1);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (1):
//ContentResolver cr = getContentResolver();
Uri contactData = data.getData();
Cursor c = getActivity().getContentResolver().query(contactData, phoneProjection, null, null, null);
if (c.moveToFirst()) {
String numbers = c.getString(0);
Log.e("Hi", numbers);
}
break;
}
}
}
you are calling getActivity().startActivityForResult(intent, 1); it's response will be handled in activity's onActivityResult() method you should call startActivityForResult(intent, 1); which is fragment's method and will call the fragments onActivityResult().
you can check this link too
I want to pass an data previous activity on click of Item in Recycler view and show it on a Edit Text.
This is the code i have used to pass data from listview to the previous activity
I want to do the same thing with Recyclerview
//Calling Second Activity
public static final int REQUEST_CODE = 100;
Intent dateintent = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(dateintent, REQUEST_CODE);
//onClick of listview pass the data back to previous activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.textView);
String str = txt.getText().toString();
Intent intent = new Intent();
intent.putExtra("data",str);
setResult(RESULT_OK,intent);
finish();
}
});
//After getting data show the data in the first activity edit box
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String data= data.getStringExtra("data");
if (data!= null) {
edittext.setText(data);
}
}
}
}
First create this Interface
public interface RunnableValue {
public void run(Object obj);
}
2.This MainActivity add
RunnableValue run=new RunnableValue() {
#Override
public Bundle run(Object obj) {
String str = obj.toString();
Intent intent = new Intent();
intent.putExtra("data",str);
setResult(RESULT_OK,intent);
finish();
}
};
mAdapter = new SearchAdapter(dataSet,run);
This RecyclerView Adapter
public SearchAdapter(List<String> dataSet,RunnableValue runnableValue) {
mDataSet = dataSet;
this.runnableValue=runnableValue;
}
public static class SearchHolder extends RecyclerView.ViewHolder {
private final TextView textView;
public SearchHolder(View v) {
super(v);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runnableValue.run(getTextView().toString());
}
});
textView = (TextView) v.findViewById(R.id.txtSearchItem);
}
public TextView getTextView() {
return textView;
}
}
Follow the Jacob's solution here. This adds listener for RecyclerView. Then, do the same as you have done in ListView.
There is no setOnItemClickListener available in RecyclerView, so you need make your own click listener in your RecyclerView adaper, just check out the post, then you should be able to make it.
Hope this help!
RecyclerView doesn't have a setOnItemClickListener like its predecessor ListView did. However, that shouldn't prevent us from doing what we want to do. So, we reinvent the wheel and make our very own OnItemClickListener for your RecyclerView. Here's a step by step guide.
Create an interface called OnItemClickListener by creating a new file called OnItemClickListener.java with an empty method called onItemClick.
public interface OnItemClickListener {
public void onItemClick(View view , int position);
}
Create a static variable in your adapter called
static OnItemClickListener mItemClickListener;
Setup onClickListener in your custom ViewHolder with a call to our onItemClick method like so
#Override
public void onClick(View view) {
mItemClickListener.onItemClick(view, getPosition());
}
Create a public method called SetOnItemClickListener in your adapter class
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener)
{
this.mItemClickListener = mItemClickListener;
}
SetOnItemClickListener on your custom RecyclerView Adapter
((NameOfYourAdapter) mAdapter).SetOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if(view != null)
{
TextView txt = (TextView) view.findViewById(R.id.textView);
String str = txt.getText().toString();
Intent intent = new Intent();
intent.putExtra("data",str);
setResult(RESULT_OK, intent);
//close this Activity...
finish();
}
}
});
That should do it. If you have any questions, feel free to ask!
I'm working on an android app that produces effects in images. I want the users of my app to have two options.
1) They can choose pictures from Gallery
2) They can capture a new photo from camera
Here is how I'm accomplishing the aforementioned two tasks:
Button takePhotoFromCameraButton;
Button chooseFromGalleryButton;
String imagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + System.currentTimeMillis() + "_image.jpg";
File imageFile = new File(imagePath);
imageUri = Uri.fromFile(imageFile);
In both buttons, I'm passing the same onClickListner.
#Override
public void onClick(View clickedView) {
int clickedViewId = clickedView.getId();
switch(clickedViewId) {
case R.id.takeFromCamera:
Intent imageCaptureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
imageCaptureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(imageCaptureIntent,0);
break;
case R.id.chooseFromGallery:
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent, 1);
break;
default:
// As we have only two buttons, and nothing else can be clicked except the buttons. So no need to put
// code in the "DEFAULT CASE"
}
}
And I'm capturing the result from both, the following way:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch(requestCode) {
case 0:
Intent cameraIntent = new Intent(MainOptionsActivity.this,ApplyEffectsActivity.class);
cameraIntent.putExtra("imageFileUri", imageUri);
startActivity(cameraIntent);
break;
case 1:
Uri imageUriForGallery = intent.getData();
Intent galleryIntent = new Intent(MainOptionsActivity.this,ApplyEffectsActivity.class);
galleryIntent.putExtra("imageFileUri", imageUriForGallery);
startActivity(galleryIntent);
break;
}
}
}
The button for gallery images works fine. But when I invoke camera by pressing the second button and capture the image, nothing happens. It stays there till I cancel the camera and come back to my app. I don't receive any image back!
Where I'm wrong? Don't mind this silly question, I'm just a beginner in android! :(
When I implemented mine, I made it work this way through a fragment:
public class ConcertFragment extends Fragment implements SurfaceHolder.Callback {
ImageView toto;
ToggleButton btnFlashlight;
RayMenu menu;
View rootView;
private Camera cam;
boolean hasCamera;
Parameters params;
private int REQUEST_IMAGE_CAPTURE;
Bitmap photo;
Uri imageUri;
public ConcertFragment() {
}
public void startCameraIntent() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
#Override
public void onStart() {
super.onStart();
SurfaceView preview = (SurfaceView)getView().findViewById(R.id.background);
SurfaceHolder mHolder = preview.getHolder();
mHolder.addCallback(this);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.concert, menu);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getCamera();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_concert, container, false);
toto = (ImageView) rootView.findViewById(R.id.toto);
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != 0)
{
if (requestCode == REQUEST_IMAGE_CAPTURE) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
toto.setImageBitmap(photo);
View content = rootView.findViewById(R.id.toto);
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg");
try {
cachePath.createNewFile();
FileOutputStream ostream = new FileOutputStream(cachePath);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
startActivity(Intent.createChooser(share,"Share via"));
}
else {
cam.release();
}
}
}
// Get the camera
private void getCamera() {
if (cam != null) {
try {
cam = Camera.open();
params = cam.getParameters();
cam.startPreview();
hasCamera = true;
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
cam.release();
}
}
}
Hope this helps :) Just ask if you need more information.
How to do it with an activity, instead of fragment
public class MyCameraActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}