Thursday, 18 June 2015

Checkbox android example

No comments
In this example we learn about Checkbox. checkbox having a two type of states checked or unchecked.here we learn a simple example one is display result in Textview and second is display toaster.

Let's go for coding.


CREATE NEW ANDROID PROJECT


Step 1: Write code into activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView

        android:id="@+id/tvDetails"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#fff" />

    <CheckBox

        android:id="@+id/cbAALink"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="https://Androidapplink.blogspot.in" />

    <CheckBox

        android:id="@+id/cbLike"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Like" />


</LinearLayout>

Step 2: Write code into MainActivity.java


package dev.androidapplink.checkboxapp;


import android.app.Activity;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

// create variables
TextView tvdetail;
CheckBox cbaalink, cblikes, cbimgicn;
OnClickListener checkBoxListener;

@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// load control
cbaalink = (CheckBox) findViewById(R.id.cbAALink);
cblikes = (CheckBox) findViewById(R.id.cbLike);

checkBoxListener = new OnClickListener() {


@Override

public void onClick(View v) {
tvdetail = (TextView) findViewById(R.id.tvDetails);

if (cbaalink.isChecked()) {

 
// set message
tvdetail.setText("Following:");
 
// get string of check box + set message (tvdetail.setText("Following:");)
tvdetail.setText(tvdetail.getText().toString() + " "
+ cbaalink.getText().toString());
}
if (cblikes.isChecked()) {

// set message

tvdetail.setText("Yes I Like");
 
// display toast
 Toast.makeText(getApplicationContext(), 
                              "Thank You", Toast.LENGTH_LONG).show();
}

if (!cbaalink.isChecked() && !cblikes.isChecked()) {

tvdetail.setText("Happy To Help");// display when both check box is unchecked

}

}
};

cbaalink.setOnClickListener(checkBoxListener);

cblikes.setOnClickListener(checkBoxListener);

}


}

Step 3: Now Run Your Project:







No comments :

Post a Comment

Follow me Share