Tutorial Membuat fragment dan Membuat intent Camera di Android
Assalamualaikum wr wb.
Pada kesempatan yang berbahagia ini saya akan menyampaikan tutorial tentang pembuatan fragmentasi activity dan camera di Android.
Buatlah project android seperti biasanya. Klik file -> New -> android aplication project. disini saya menamakan nya "Magicjar".
Tambahkan file activity dan fragment ke dalam folder src sebagai berikut:
- App2Activity
- CameraPreview
- Kamera2
- FragMent1
- FragMent2
- FragMent3
- MainActivity
App2Activity Menampilkan activity yang menampung 3 fragment, FragMent1, FragMent2, FragMent3. berikut source code nya.
public class App2Activity 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("Listing").setTabListener(this));
bar.addTab(bar.newTab().setText("Image").setTabListener(this));
bar.addTab(bar.newTab().setText("Details").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("Listing")) {
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("Image")) {
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("Details")) {
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
}
}
Activity CameraPreview digunakan untuk menampilkan gambar tangkapan kamera. berikut source code nya:
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
}
}
Sememtara Activity Kamera2 digunakan untuk menampung device kamera nya dan ngetur konfigurasi lain seperti method OnCreate, OnResume, OnPause, dan konfigurasi path penyimpanan gambar yang di tangkap kamera.
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
}
}
Dan ini untuk FragMent1 yang berisi seperti list.
public class FragMent1 extends Fragment {
private String arry[] = { "Example", "N 14 M", "Fragment" };
@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;
}
}
Dan ini untuk FragMent2 yang berisi gridlist image.
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.drum);
return convertView;
}
}
}
Dan ini untuk FragMent3 yang berisi menampilkan fragmen yang berisi image.
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.drum);
return convertView;
}
}
}
Dan untuk MainActivity nya
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, App2Activity.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;
}
}Secara lengkap file activity dan fragment nya adalah:
Setelah kita membuat file file activity dan fragment nya, kita sekarang akan membuat file layout nya. buat file layout dengan memilih file -> new -> android XML file.ada 4 file yang akan di buat:
- activity_main
- gridview
- kamera
- main2
Berikut masing2 source nya:
activity_main
<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>
gridview
<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:background="@drawable/carbon"
android:horizontalSpacing="5dp"
android:numColumns="5"
android:id="@+id/mainGrid"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp" >
</GridView>
</RelativeLayout>
kamera
<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="Jepret" />
</RelativeLayout>
main2
<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/carbon"
android:id="@+id/mainLayout">
</RelativeLayout>
perbaharui pula file string.xml di folder res/values.
<resources>
<string name="app_name">Magicjar</string>
<string name="action_settings">Settings</string>
<string name="buton1">Aplikasi 1 </string>
<string name="buton2">Aplikasi Kamera </string>
<string name="Header">Ini Halaman Muka</string>
<string name="ganti">Contoh Fragment</string>
<string name="cannot">cannot</string>
<string name="album_name">CameraSample</string>
</resources>
jangan lupa meng-update AndroidManifest dengan menambah code di bawah ini sebelum tag </aplication>
<activity
android:name="com.example.magicjar.App2Activity"
android:label="@string/app_name">
</activity>
<activity
android:name="com.example.magicjar.Kamera2"
android:label="@string/app_name"
android:screenOrientation="landscape"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:configChanges="keyboardHidden|orientation">
</activity>
Jika berhasil tampilan program anda akan seperti ini:
Activity_main
Fragment1
Fragment2
Fragment3
Kamera
Tambahkan pula file gambar yang anda masukkan ke project dengan meng-copy file tersebut seperti biasa ke folder res/drawable-hdpi. berikut saya sertakan image yang saya tambah ke project.
carbon.png
drum.png
Jikalau masih mengalami kesulitan, silahkan download source code lengkapnya di sini
Referensi:
developer.android.com
agungrachmatullah.wordpress.com
Sekin yang bisa saya sampaikan. apabila ada pertanyaan silahkan tuliskan di kolom komentar.
Wassalamualaikum wr. wb.
link mati, harap di perbaiki
BalasHapusterima kasih