Belajar Membuat Tab dan Panggil Camera Di Android

source : https://www.medicalcenter.virginia.edu


Android, lanjutan dari postingan sebelumnya. Kali ini kita belajar UI dengan tab juga belajar memanggil kamera. Yuk simak bareng-bareng..
Source code ini saya dapat dari hasil nyari, terus docs dari android, dari dosen juga.



Buat project nya terlebih dahulu


Buat 6 class pada package, yang 3 sebagai isi fragment (FragMent1, FragMent2, Fragment3), 1 sebagai headnya fragment (HeadFragment), 1 sebagai camera (Kamera2), dan 1 lagi untuk preview gambar dari camera (CameraPreview).
Selanjutnya kita bikin 3 tambahan layout, yang satu untuk layoutnya fragment (main2), yang satu untuk layout camera (kamera), yang terakhir untuk menampilkan salah satu dari fragment (grid).


Setelah itu kita mulai codingnya, karena kita akan menggunakan camera, jangan lupa tambahkan permissionnya pada AndroidManifest nya agar camera dapat di akses.

Tambahkan source dibawah ke AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
      <uses-feature android:name="android.hardware.camera"/>
      <uses-feature android:name="android.hardware.camera.autofocus" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Pastikan pada activity di AndroidManifest.xml sudah sesuai dengan urutan 

--AndroidManifest.xml --

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.tictoc.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.example.tictoc.HeadFragment"
            android:label="@string/app_name">
           
        </activity>
        <activity
            android:name="com.example.tictoc.Kamera2"
            android:label="@string/app_name"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:configChanges="keyboardHidden|orientation">
        </activity>
       
    </application>

Lanjut ke MainActivity.java

--MainActivity.java--

package com.example.tictoc;

import com.example.tictoc.R;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

      Button button1;
      Button button2;
      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            addListenerOnButton();
           
      }
      public void addListenerOnButton() {
             
        final Context context = this;

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(context, HeadFragment.class);
                            startActivity(intent);
            }    
        });

        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(context, Kamera2.class);
                            startActivity(intent);
            }
        });
    }

      @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;
      }

}

Disini kita mengaktifkan button yang sudah dibuat pada layout/activity_main.xml agar dapat di jalankan ketika memilih button tersebut.

Untuk activity_main.xml kurang lebih seperti dibawah, ada 2 button yang satu Tab, yang satu Camera. Jangan lupa setting android text nya di string.xml

--main_activity.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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp"
        android:text="@string/buton1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"
        android:text="@string/buton2" />
</RelativeLayout>

Untuk Tab, disini isinya 3 fragment. Yang pertama Tab List, berisi teks secara list urutannya. Yang kedua ada gambar grid-grid, yang ketiga ada teks biasa. Untuk code pada headfragmentnya :

--HeadFragment.java--
package com.example.tictoc;

import com.example.tictoc.R;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.widget.RelativeLayout;
@SuppressLint("NewApi")
public class HeadFragment extends Activity implements TabListener{

      RelativeLayout rl;
       
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main2);
            try {
                  rl = (RelativeLayout) findViewById(R.id.mainLayout);
                  fragMentTra = getFragmentManager().beginTransaction();
                  ActionBar bar = getActionBar();
                  bar.addTab(bar.newTab().setText("List").setTabListener(this));
                  bar.addTab(bar.newTab().setText("Grid").setTabListener(this));
                  bar.addTab(bar.newTab().setText("Teks").setTabListener(this));

                  bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
                              | ActionBar.DISPLAY_USE_LOGO);
                  bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
                  bar.setDisplayShowHomeEnabled(true);
                  bar.setDisplayShowTitleEnabled(false);
                  bar.show();

            } catch (Exception e) {
                  e.getMessage();
            }
            /**
             * Hiding Action Bar
             */
      }
     
      FragMent1 fram1;
      FragmentTransaction fragMentTra = null;
      FragMent2 fram2;
      FragMent3 fram3;
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
      }

      @Override
      public void onTabReselected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub
           
      }

      @Override
      public void onTabSelected(Tab tab, FragmentTransaction ft) {

            if (tab.getText().equals("List")) {
                  try {
                        rl.removeAllViews();
                  } catch (Exception e) {
                  }
                  fram1 = new FragMent1();
                  fragMentTra.addToBackStack(null);
                  fragMentTra = getFragmentManager().beginTransaction();
                  fragMentTra.add(rl.getId(), fram1);
                  fragMentTra.commit();
            } else if (tab.getText().equals("Grid")) {
                  try {
                        rl.removeAllViews();
                  } catch (Exception e) {
                  }
                  fram2 = new FragMent2();
                  fragMentTra.addToBackStack(null);
                  fragMentTra = getFragmentManager().beginTransaction();
                  fragMentTra.add(rl.getId(), fram2);
                  fragMentTra.commit();
            } else if (tab.getText().equals("Teks")) {
                  try {
                        rl.removeAllViews();
                  } catch (Exception e) {
                  }
                  fram3 = new FragMent3();
                  fragMentTra.addToBackStack(null);
                  fragMentTra = getFragmentManager().beginTransaction();
                  fragMentTra.add(rl.getId(), fram3);
                  fragMentTra.commit();
            }

      }

      @Override
      public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub 
      }
}

Untuk semua fragment mempunyai background, sehingga kita setting backgroundnya di main2.xml

--main2.xml--

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/squirrel"
    android:id="@+id/mainLayout">   
</RelativeLayout>

Code dari FragMent1.java yang isinya list-list, yaitu Arief Satriana Ulfa, PM, sama Halo.

--FragMent1.java--

package com.example.tictoc;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

@SuppressLint("NewApi")
public class FragMent1 extends Fragment {

      private String arry[] = { "Arief Satriana Ulfa", "PM", "Halo" };

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                  Bundle savedInstanceState) {
            ListView listView = new ListView(getActivity());
            ArrayAdapter<String> array = new ArrayAdapter<String>(getActivity(),
                        android.R.layout.simple_list_item_1);
            for (String str : arry)
                  array.add(str);
            listView.setAdapter(array);
            return listView;
      }
}

Untuk fragment grid, isi dari FragMent2.xml . Untuk gambar yang akan jadi grid-grid bisa di atur disini

--FragMent2.java--

package com.example.tictoc;

import com.example.tictoc.R;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

@SuppressLint("NewApi")
public class FragMent2 extends Fragment {

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                  Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.gridview, null);
            GridView listView = (GridView) view.findViewById(R.id.mainGrid);
            listView.setAdapter(new Adapter());
            return view;
      }

      private class Adapter extends BaseAdapter {

            @Override
            public int getCount() {
                  return 30;
            }

            @Override
            public Object getItem(int position) {
                  return null;
            }

            @Override
            public long getItemId(int position) {
                  // TODO Auto-generated method stub
                  return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                  ImageView image;
                  if (convertView == null) {
                        image = new ImageView(FragMent2.this.getActivity());
                        image.setLayoutParams(new GridView.LayoutParams(100, 100));
                        image.setScaleType(ScaleType.FIT_XY);
                        convertView = image;
                  } else {
                        image = (ImageView) convertView;
                  }
                  image.setBackgroundResource(R.drawable.bg);
                  return convertView;
            }
      }
}

Lalu dilanjut di gridview.xml

--gridview.xml--

<?xml version="1.0" encoding="utf-8"?>
<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" >

    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:horizontalSpacing="5dp"
        android:numColumns="5"
        android:id="@+id/mainGrid"
        android:stretchMode="columnWidth"
        android:verticalSpacing="5dp" >
    </GridView>

</RelativeLayout>


Setelah itu di tab Teks (ketiga) hanya berisi teks biasa

--FragMent3.xml--

package com.example.tictoc;

import com.example.tictoc.R;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

@SuppressLint("NewApi")
public class FragMent3 extends Fragment {

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                  Bundle savedInstanceState) {
            TextView teks = new TextView(getActivity());
            teks.setText("Halo");
            return teks;
      }
}

Sekarang lanjut di kamera. Dalam pemanggilan kamera ada 2 cara, langsung ke kamera bawaan atau seolah-olah kita membuat aplikasi kamera sendiri. Nah yang akan dicoba disini adalah yang kedua. Langsung nyimak aja, di awal kita sudah membuat 2 button. Yang kedua adalah kamera, disini dia akan lari ke kamera2.java sesuai activity yang ada di AndroidManifest.xml

--Kamera2.java--

package com.example.tictoc;

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.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;

public class Kamera2 extends Activity {

      public static final int MEDIA_TYPE_IMAGE = 1;
      private Camera mCamera;
    private CameraPreview mPreview;
    final static String TAG = "PAAR";
      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
      }
     
      /**
       * @param args
       */
      @Override
      protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.kamera);
           
            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.kameraPreview);
        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) {

                }
              }
            };
        Button bcam= (Button) findViewById(R.id.buttonKam);
        bcam.setOnClickListener(new OnClickListener() {
                 
                  @Override
                  public void onClick(View v) {
                        // TODO Auto-generated method stub
                        System.out.println("Photo Taking!");
                        mCamera.takePicture(null, null, mPicture);
                  }
            });
       
       
      }
      @Override
    protected void onPause() {
        super.onPause();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }


    private void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }
     
      private static Uri getOutputMediaFileUri(int type){
            return Uri.fromFile(getOutputMediaFile(type));
      }

      /** Create a File for saving an image or video */
      private static 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()){
                  Log.d("MyCameraApp", "failed to create directory");
                  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;
      }
     
      public static void main(String[] args) {
            // TODO Auto-generated method stub
      }
}

Untuk kamera.xmlnya sendiri

--Kamera.xml--

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
   
      <FrameLayout
            android:id="@+id/kameraPreview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

      <Button
          android:id="@+id/buttonKam"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentRight="true"
          android:layout_centerVertical="true"
          android:layout_marginRight="14dp"
          android:text="Ambil" />

</RelativeLayout>


Setelah mengambil gambar, pastinya ada preview gambar yang sudah diambil


--CameraPreview.java--

package com.example.tictoc;

import java.io.IOException;

import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
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("CameraPreview", "Error starting camera preview: " + e.getMessage());
        }
    }

      /**
       * @param args
       */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
      }
}


Untuk hasil projeknya kurang lebih seperti dibawah 

Main

List

Grid

Teks

Camera


 Terima kasih..
Mohon kritik sarannya :)

Komentar

Dev Notes mengatakan…
Mantap.. bermanfaat..:D