简体   繁体   中英

Button in one activity to do the same as button in another activity

I am new to Android. In my application, in ActivityOne I want to allow the user to take a picture using a button. The picture is then stored in the gallery and displayed in an ImageView in ActivityTwo. My question is: How can I add a button to ActivityTwo that allows the user to retake the picture if they don't like it when displayed in the ImageView. Basically, the button will do the same as the one in ActivityTwo. Do I need to write the same code for the button? I have tried to create a separate that implements View.OnClickListener, add the functionality in the onClick method, and in each activity create an instance of that class attached to the button:

onClick(View v) { 
int id = v.getId();
if (id == R.id.myButton) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
myfile = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
v.startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
   }
}

However, this causes errors as the class is not an activity. Any help is appreciated.

You can write the same logic for this second button, but as Naveen mentioned it would be easier to put the button on the first activity, leading to the camera. When the user takes a picture just add an imageview to the layout above the button using linearlayout on the first activity. Then the picture is displayed and the user has the option to retake it.

The best option is to let the user take the picture in the activity where it is needed. But if there is a need for you to use it in multiple places, you should extract the code triggered by the button in the first activity(The code that takes the picture) into a separate class. then you can call it from anywhere when needed.

@Subzero-273k Follow this.

  1. In your activity make two different layouts. One, which shows your first button, remember to hide the other layout by setting the visibility.
  2. Once user clicked the button1 which calls someOnClick(), hide first layout and enable another layout, which shows you the imageView and button2, onclick of button2 still calls your old function someOnClick().

How about this? As you dint mention what else you are doing in two different activities, I assume you just show activity one for single button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM