Subscribe:

Rabu, 10 Juli 2013

Membuat Check Box pada Aplikasi Android

Kadang kita membutuhkan sebuah checkBox misalnya untuk memilih beberapa pilihan. Pada bab ini kita akan berlatih menggunakan widget CheckBox, ketika checkbox aktif tulisan berbunyi “checkini:icentang!” dan saat check tidak aktif tulisan berbunyi "checkBox ini: tidak dicentang!". asil previewnya seperti gambar 1.1 
image
Gambar 1.1
Berikut adalah Langkah-Langkahnya:
  1. Jalankan Enclipse, buat Project baru.
  2. Isilah parameter seperti berikut
    Project name MembuatCheckBox
    Contents Create new project in workspace
    Build Target Android 2.1
    Application name Membuat Check Box
    Package name contoh.checkBox
    Create Activity checkBox
    Min SDK version 7
  3. Perhatikan kode pada String.xml. (res/values/string.xml). Tambahkan kode menjadi seperti berikut :
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="hello">Hello World,
    checkBox!</string>
        <string name="app_name">Membuat Check Box</string>
        <string name="checkBox">checkBox ini : Tidak
    Dicentang!</string>
    </resources>
  4. Kemudian ketikkan kode berikut ini pada main.xml.
    <?xml version="1.0" encoding="utf-8"?>
        <CheckBox
    xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
         android:id="@+id/check"
    android:layout_height="wrap_content" android:text="@string/checkBox">
    </CheckBox>
  5. Tuliskan  kode checkBox.java seperti berikut
    package contoh.checkBox;
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import
    android.widget.CompoundButton.OnCheckedChangeListener;
    public class checkBox extends Activity implements
    OnCheckedChangeListener {
      CheckBox cb;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            cb=(CheckBox)findViewById(R.id.check);
            cb.setOnCheckedChangeListener(this);
        }
        public void onCheckedChanged(CompoundButton
    buttonView,
            boolean isChecked) {
            if (isChecked) {
            cb.setText("checkBox ini : Dicentang!");
            }
            else {
            cb.setText("checkBox ini : Tidak Dicentang!");
            }
            }
    }
  6. Bila kode berantakan, lakukan Format (source > format).
  7. Lakukan RUN dan lihat hasilnya


0 komentar:

Posting Komentar