Tutorial Android Tab & Camera

Gimana sih?

Gimana sih cara membuat menu tab dan camera pada android? Ok, tutorial ini akan membahas tentang menu tab dan camera pada Android. sebelum masuk ke tutorial, saya rekomendasi untuk lebih tahu dulu tentang fragment.

Singkatnya, fragment merepresentasikan behavior atau bagian dari user interface pada activity. Kita dapat menggabungkan banyak fragment dalam sebuah activity atau menggunakan ulang sebuah fragment untuk banyak activity. Biar lebih gamblang lagi, berikut gambarannya :

Gambar1. Jadi fragment dapat digabungkan dalam satu activity dan sebaliknya.

Untuk membuat fragment, kita harus membuat subclass dari fragment. Class Fragment didalamnya terdapat code yang sangat mirip seperti Activity. Didalamnya terdiri dari method callback yang mirip dengan activity, seperti onCreate(), onStart(), onPause(), dan onStop().

Picture2

 Penjelasan singkat :

onCreate()
Sistem akan memanggil method ini saat membuat fragment.
onCreateView()
Sistem akan memanggil methid ini saat fragment akan membuat atau menggambar UI untuk pertama kalinya.
onPause()
Yang terakhir, method ini akan dipanggil  ada indikasi bahwa user sedang tidak berinteraksi dengan fragment.

Nah, dari pada bingung kita mulai langsung aja. Berikut langkah-langkahnya :

  1. Buat project baru.
  2. Buat halaman utama interface pada activity_main.xml.
  3. Buat kelas utama program.
  4. Edit androidmanifest.xml.

Halaman utama

Buat project baru.

File->New->Android Application Project

Kemudian masuk ke folder res->layout->activity_main.

Editlah tag “relativelayout” hingga menjadi  demikian,

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context="com.bagus.tabandcamera.MainActivity$PlaceholderFragment" >

Kenapa layout Linear? agar layout akan tertata secara linear. “match_parrent” berarti lebar dan tinggi layout akan sama dengan lebar dari parrent layout itu.

Kemudian tambahkan code berikut :

<TextView
 android:id="@+id/textView1"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_marginBottom="10dp"
 android:layout_marginTop="10dp"
 android:gravity="center"
 android:text="Tutorial tab dan kamera"
 android:textAppearance="?android:attr/textAppearanceLarge"
 android:textStyle="bold" />
<Button
 android:id="@+id/tabBtn"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Tab" />
<Button
 android:id="@+id/cameraBtn"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Camera" />
</LinearLayout>

Buat kelas utama program.

Edit lah class utama di src->com.bagus.tabandcamera hingga menjadi seperti berikut :

package com.bagus.tabandcamera;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
 Button tab, camera;
@Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 tab = (Button) findViewById(R.id.tabBtn);
 camera = (Button) findViewById(R.id.cameraBtn);
 tab.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 Intent i = new Intent(MainActivity.this, TabActivity.class);
 startActivity(i);
 }
 });
 camera.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 Intent i = new Intent(MainActivity.this, CameraActivity.class);
 startActivity(i);
 }
 });
 }
@Override
 public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.main, menu);
 return true;
 }
@Override
 public boolean onOptionsItemSelected(MenuItem item) {
 // Handle action bar item clicks here. The action bar will
 // automatically handle clicks on the Home/Up button, so long
 // as you specify a parent activity in AndroidManifest.xml.
 int id = item.getItemId();
 if (id == R.id.action_settings) {
 return true;
 }
 return super.onOptionsItemSelected(item);
 }
}

Edit androidmanifest.xml.

Jangan lupa kita edit androidanifest.xml. Ini berisi tentang identitas dari aplikasi yang akan dibuat.

<?xml version="1.0" encoding="utf-8"?>
 package="web.id.hemm.tabandcamera"
 android:versionCode="1"
 android:versionName="1.0" >
<uses-sdk
 android:minSdkVersion="14"
 android:targetSdkVersion="19" />
 <uses-feature android:name="android.hardware.camera"/>
 <uses-permission android:name="android.permission.CAMERA"/>
 <uses-feature android:name="android.hardware.camera.autofocus" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name="com.bagus.tabandcamera.MainActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 <activity
 android:name="com.bagus.tabandcamera.TabActivity"
 android:label="@string/tab"
 android:parentActivityName="web.id.hemm.tabandcamera.MainActivity">
 </activity>
 <activity
 android:name="com.bagus.tabandcamera.CameraActivity"
 android:label="@string/camera"
 android:parentActivityName="com.bagus.tabandcamera.MainActivity"
 android:screenOrientation="landscape">>
 </activity>
 </application>
</manifest>
Screenshot_2014-04-09-12-49-36

Setelah itu buat class baru pada package dengan nama TabActivity.java dan CameraActivity.java, karena pada code diatas OnClickListener akan mencari TabActivity.java dan CameraActivity.java. Untuk membuat class baru, klik kanan pada package, new class.

 

Layout Tab

Langkah-langkah membuat layout tab :

  1. Buat layout baru.
  2. Buat layout dan class untuk masing fragment.
  3. Buat class baru untuk menghandle tab yang sudah dibuat.
  4. Edit class TabActivity.

Buat layout baru.

klik kanan pada project lalu pilih layout > New > Android XML File. Dan edit hingga menjadi :

<!-- activity_tab -->
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/pager"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

Buat layout dan class untuk masing fragment.

Tab “Top Rated

Klik kanan > New di folder layout (res > layout) kemudian pilih Android XML File

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 android:background="#fa6a6a"
 android:gravity="center" >
<TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Design Top Rated Screen"
 android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>

Klik kanan pada src > New > Class. Lakukan cara yang sama untuk TabFragment berikutnya.

package com.bagus.tabandcamera;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TopRatedFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
        return rootView;
    }
}

Buat hingga terdapat 3 buah tab yaitu : TOP RATED, MOVIE, GAME.

Buat class baru untuk menghandle tab yang sudah dibuat.

Buat class baru dengan nama TopPageAdapter.java. Kemudian masukan  code berikut ini :

package com.bagus.tabandcamera;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter{
public TabPagerAdapter(FragmentManager fm) {
 super(fm);
 // TODO Auto-generated constructor stub
 }
@Override
 public Fragment getItem(int index) {
 // TODO Auto-generated method stub
 switch(index){
 case 0:
 return new TopRatedFragment();
 case 1:
 return new GamesFragment();
 case 2:
 return new MovieFragment();
 }
 return null;
 }
@Override
 public int getCount() {
 // get item count - equal to number of tabs
 return 3;
 }
}

Edit class TabActivity.

package com.bagus.tabandcamera;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class TabActivity extends FragmentActivity implements ActionBar.TabListener{
 private ViewPager viewPager;
 private TabPagerAdapter mAdapter;
 private ActionBar actionBar;
 private String[] tabs = {"Top Rated", "Games", "Movie"};
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_tab);
 viewPager = (ViewPager) findViewById(R.id.pager);
 actionBar = getActionBar();
 mAdapter = new TabPagerAdapter(getSupportFragmentManager());
 viewPager.setAdapter(mAdapter);
 actionBar.setHomeButtonEnabled(true);
 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
 //Adding Tabs
 for(String tab_name : tabs){
 actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
 }
 viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
 @Override
 public void onPageSelected(int position) {
 // TODO Auto-generated method stub
 actionBar.setSelectedNavigationItem(position);
 }
 @Override
 public void onPageScrolled(int arg0, float arg1, int arg2) {
 // TODO Auto-generated method stub
 }
 @Override
 public void onPageScrollStateChanged(int arg0) {
 // TODO Auto-generated method stub
 }
 });
 }
@Override
 public void onTabSelected(android.app.ActionBar.Tab tab,
 FragmentTransaction ft) {
 // TODO Auto-generated method stub
 viewPager.setCurrentItem(tab.getPosition());
 }
@Override
 public void onTabUnselected(android.app.ActionBar.Tab tab,
 FragmentTransaction ft) {
 // TODO Auto-generated method stub
 }
@Override
 public void onTabReselected(android.app.ActionBar.Tab tab,
 FragmentTransaction ft) {
 // TODO Auto-generated method stub
 }
}

Dan hasilnya jika di compile :

5

Camera

Nah, sekarang kita masuk ke tutorial aplikasi camera.  Buat layout baru lagi dengan nama activity_camera.xml, lalu editlah menjadi :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
/>
<Button
android:id="@+id/captureBtn"
android:text="Capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>
Kalau aplikasi camera ini memang agak panjang, dan di documensi developer.android sudah lengkap, jadi kebanyakan copas saja😀.
Buat class baru dengan nama CameraPreview.java, yang akan menampilkan gambar hasil jepretan kamera.
package com.bagus.tabandcamera;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
 private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
 super(context);
 mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
 // underlying surface is created and destroyed.
 mHolder = getHolder();
 mHolder.addCallback(this);
 // deprecated setting, but required on Android versions prior to 3.0
 //mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
 }
public void surfaceCreated(SurfaceHolder holder) {
 // The Surface has been created, now tell the camera where to draw the preview.
 try {
 mCamera.setPreviewDisplay(holder);
 mCamera.startPreview();
 } catch (IOException e) {
 Log.d("CameraPreview", "Error setting camera preview: " + e.getMessage());
 }
 }
public void surfaceDestroyed(SurfaceHolder holder) {
 // empty. Take care of releasing the Camera preview in your activity.
 }
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
 // If your preview can change or rotate, take care of those events here.
 // Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
 // preview surface does not exist
 return;
 }
// stop preview before making changes
 try {
 mCamera.stopPreview();
 } catch (Exception e){
 // ignore: tried to stop a non-existent preview
 }
// set preview size and make any resize, rotate or
 // reformatting changes here
// start preview with new settings
 try {
 mCamera.setPreviewDisplay(mHolder);
 mCamera.startPreview();
} catch (Exception e){
 Log.d("CaameraPreview", "Error starting camera preview: " + e.getMessage());
 }
 }
}
Dan yang terakhir, edit class CameraActivity.java menjadi :
package web.id.hemm.tabandcamera;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.ActionBar;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
public class CameraActivity extends Activity {
    private Camera mCamera;
    private CameraPreview mPreview;
    public static final int MEDIA_TYPE_IMAGE = 1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        Button captureButton = (Button) findViewById(R.id.captureBtn);
        System.out.println("Starting!");
        // Create an instance of Camera
        mCamera = getCameraInstance();
        // Create our Preview view and set it as the content of our activity.
        mPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mPreview);
        final PictureCallback mPicture = new PictureCallback() {
            public void onPictureTaken(byte[] data, Camera camera) {
                File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
                if (pictureFile == null){
                    return;
                }
                try {
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    fos.write(data);
                    fos.close();
                    MediaStore.Images.Media.insertImage(getContentResolver(), pictureFile.getAbsolutePath(), pictureFile.getName(), pictureFile.getName());
                } catch (FileNotFoundException e) {
                } catch (IOException e) {
                }
              }
            };
         // Add a listener to the Capture button
            captureButton.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View v) {
                        // get an image from the camera
                        System.out.println("Photo Taking!");
                        mCamera.takePicture(null, null, mPicture);
                    }
                }
            );
    }
    // A safe way to get an instance of the Camera object.
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }
    @Override
    protected void onPause() {
        super.onPause();
        releaseCamera();              // release the camera immediately on pause event
    }
    private void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }
    // Create a File for saving an image or video
    private  File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                  Environment.DIRECTORY_PICTURES), "MyCameraApp");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.
        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "IMG_"+ timeStamp + ".jpg");
        } else {
            return null;
        }
        return mediaFile;
    }
    }
Dan hasilnya :
Screenshot_2014-04-09-12-49-36

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s