按钮500x500的图像。
我创建了ImageButton
,当点击ImageButton
时系统相机应该启动,系统相机应用程序带来的图像将显示在ImageView
中。但问题是:按钮在这里不起作用。除了按钮,如果我点击应用程序中的任何位置,系统摄像头将启动,但如果按下按钮,相机将无法启动。什么样的错误导致了这种意外行为?
Java文件:
public class Home extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// CAMERA BUTTON IMPLEMENTATION
ImageButton cameraButton = (ImageButton)findViewById(R.id.imageButton);
imageView = (ImageView)findViewById(R.id.imageView);
/* Disable the button if the user doesn't have camera */
if(!hasCamera())
cameraButton.setEnabled(false);
// CAMERA BUTTON IMPLEMENTATION
}
// Check if the user has a camera
private boolean hasCamera(){
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
// Launching the camera
public void launchCamera(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Take a picture and pass results along to onActivityResult
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
// If you want to return the image taken
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
//Get the photo
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
imageView.setImageBitmap(photo);
}
}
}
XML文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.muchmore.www.chasquido.Home"
android:background="@drawable/home_background"
android:id="@+id/home_activity"
android:onClick="launchCamera">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome User!!!"
android:id="@+id/welcome_tag"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#000"
/>
<ImageButton
android:layout_width="90dp"
android:layout_height="90dp"
android:id="@+id/imageButton"
android:background="@drawable/camera_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:minHeight="300dp"
android:minWidth="300dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
答案 0 :(得分:1)
您已将OnClickListener
android:onClick="launchCamera"
分配给RelativeLayout
(您的根视图),而不是ImageButton
。