Taking a Picture in Android
Create a new project in Eclipse from File ⇒ New ⇒ Android ⇒ Application Project and fill all the required information. I left my main activity as MainActivity.java
Working with camera needs set of permissions and features in the AndroidManifest.xml file. Add following in your AndroidManifest.xml
android.hardware.camera – Required to use camera hardware
Adding required permissions in manifest file |
Open your layout file of your main activity activity_main.xml and paste the following code.
Here layout consists of a button and imageview.
<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"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text="@string/take_pic" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="115dp"
android:contentDescription="@string/TODO"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
Go to mainactivity java class and copy the following codes:
public class MainActivity extends Activity {
Button b;
ImageView iv;
Bitmap bm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView1);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 0);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bitmap);
}
Now the project is ready to run.
No comments:
Post a Comment
Did this post help you? Do you have any questions? Drop your thoughts here...