24 December 2014

Code for simple ToggleButton in Android

android toggle button
What will we do ?
-> We will make a Simple Toggle Button and display a Toast when its state is changed.

What we will need ?
  • Additions in activity_main.xml
  • ToggleButton
  • TextView
  • Toast
  • Additions in MainActivity.java
Step 1 : Create a New Project form File->New->Android Application Project.

Step 2 : Give a Name to the Project and Click on Next...... then Finish.

Step 3 : Open activity_main.xml found in res->layout folder from Project Explorer (already opened). Drag ToggleButton and a TextView on the Layout and then click on activity_main.xml as shown below.
activity_main.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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="35dp"
        android:text="Press to change state"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="36dp"
        android:text="ToggleButton"
    android:onClick="onToggleClicked" />

</RelativeLayout>



Step 4 : Open MainActivity.java from src folder.

MainActivity.java 

package com.example.toggledemo;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.app.Activity;

public class MainActivity extends Activity {

    ToggleButton tb1;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tb1 = (ToggleButton) findViewById(R.id.toggleButton1);
        

    }
    public void onToggleClicked(View view) {
        
        boolean on = ((ToggleButton) view).isChecked();
        
        if (on) {
            Toast.makeText(MainActivity.this, "It is ON",Toast.LENGTH_SHORT).show();
        }
            
        else {
            Toast.makeText(MainActivity.this, "It is OFF",Toast.LENGTH_SHORT).show();            
        }
       }
}


Step 5 : Run the Project.

Explanation of the code:
 Explanation for activity_main.xml
  • A TextView just to show that you have to click the button below (optional)
<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="35dp"
        android:text="Press to change state"
        android:textAppearance="?android:attr/textAppearanceLarge"/>
  • A toggle button with id toggleButton1 for changing between states (like True/False) using a single Button.
<ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="36dp"
        android:text="ToggleButton"
    android:onClick="onToggleClicked" />

Explanation of code from MainActivity.java
  •  Made an instance of ToggleButton called tb1.
ToggleButton tb1;
  • Match the instance declared above to the ToggleButton actually found in the activity_main.xml with id toggleButton1
tb1 = (ToggleButton) findViewById(R.id.toggleButton1);
  •  Define an overridden method called onToggleClicked() to specify what happens when ToggleButton is clicked.
public void onToggleClicked(View view) {
  • Make a boolean variable to store the ON state of the button by using isChecked() method.
boolean on = ((ToggleButton) view).isChecked();
  • If the ToggleButton is ON display Toast as "Button is ON" else display Toast "Button is OFF"
if (on) {
            Toast.makeText(MainActivity.this, "It is ON",Toast.LENGTH_SHORT).show();
        }
            
        else {
            Toast.makeText(MainActivity.this, "It is OFF",Toast.LENGTH_SHORT).show();            
        }

Github download
Stay Tuned with Made In Android

Published By:
Yatin Kode
on 24.12.14

16 December 2014

Code for a Check-Box in Android

Here we will learn to make a check-box and various actions in check-box with an example and total explanation of the code .

What we will need ?
  • A layout(activity_main.xml)
  • A Java Source (MainActivity.java)
  • 3 Check-boxes
  • Toast
Step 1 : Create a new Android Application by clicking on File->New-> Android Application Project.
file new

Step 2 : Give a suitable name to your Project and a package name also (CheckBoxDemo).
name checkbox
Click Next on other steps till you exit the small window (at last click Finish).

Step 3 : Design the xml layout for our Application (activity_main.xml) found in res->layout form the Project Explorer.
drag checkbox pallete
activity_main.xml 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<CheckBox
    android:id="@+id/chickenCB"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Chicken" />

<CheckBox android:id="@+id/fishCB" 
    android:text="Fish"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<CheckBox android:id="@+id/steakCB"
    android:text="Steak"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>


Step 4 :Design the code for java back-end in MainActivity.java found in src folder from Project Explorer.

MainActivity.java 
package com.mia.checkboxdemo;

import android.os.Bundle;
import android.app.Activity;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final CheckBox fishCB = (CheckBox)findViewById(R.id.fishCB);
        final CheckBox chickenCB = (CheckBox)findViewById(R.id.chickenCB);
        final CheckBox steakCB = (CheckBox)findViewById(R.id.steakCB);
        
    fishCB.setOnCheckedChangeListener(
            new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
                    if(fishCB.isChecked()==false)
                        Toast.makeText(getApplicationContext(), "Fish not selected", Toast.LENGTH_SHORT).show();    
                    else
                        Toast.makeText(getApplicationContext(), "Fish Selected", Toast.LENGTH_SHORT).show();
                }});
    
chickenCB.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
                
                if(chickenCB.isChecked()==false)
                    Toast.makeText(getApplicationContext(), "Chicken not selected", Toast.LENGTH_SHORT).show();    
                else
                    Toast.makeText(getApplicationContext(), "Chicken Selected", Toast.LENGTH_SHORT).show();
                        
            }});
    
if(steakCB.isChecked())
    steakCB.toggle();  // flips the checkbox to unchecked if it was checked
steakCB.setOnCheckedChangeListener(
    new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
            
            if(steakCB.isChecked()==false)
                Toast.makeText(getApplicationContext(), "Steak not selected", Toast.LENGTH_SHORT).show();    
            else
                Toast.makeText(getApplicationContext(), "Steak Selected", Toast.LENGTH_SHORT).show();
        }});
    
    }
    }


Step 5 : Run the Project.
chicken fish checkchicken not check
Explanation of the code :
  1. Explanation from activity_main.xml
  • We drag three check-boxes from the Palette and add text for the display of Fish Chicken and Steak. We assign the ids fishCB, chickenCB and steakCB respectively.
  • In the check-box code of Fish the statement 
android:checked="true"
          says that it will be previously checked(ticked) before running the project.
  • Others by default will be unchecked (not ticked).
      2.  Explanation of MainActivity.java
  • We define the variables of type CheckBox for our check-boxes using method findViewById() an the ids present in R.java.
final CheckBox fishCB = (CheckBox)findViewById(R.id.fishCB);
        final CheckBox chickenCB = (CheckBox)findViewById(R.id.chickenCB);
        final CheckBox steakCB = (CheckBox)findViewById(R.id.steakCB);
fishCB.setOnCheckedChangeListener(
            new CompoundButton.OnCheckedChangeListener()
         It just maintains the state of the check-box(checked or unchecked).
  • Then a method is defined in it named onCheckedChanged() in which we define out actual code. We use an if-else loop.
public void onCheckedChanged(CompoundButton arg0, boolean isChecked)
  • In the if part we we make a Toast for the check-box being unchecked by checking if isChecked() method returns false value else the vice-versa.We repeat the same procedure for the remaining 2 check-boxes.
if(chickenCB.isChecked()==false)

Toast.makeText(getApplicationContext(), "Chicken not selected", Toast.LENGTH_SHORT).show();    

else

Toast.makeText(getApplicationContext(), "Chicken Selected", Toast.LENGTH_SHORT).show();

 }});

Github download

Stay Tuned with Made In Android

Published By:
Yatin Kode
on 16.12.14

11 December 2014

Make a Toast in Android

What we will need ?
  • activity_main.xml
  • MainActivity.java
  • 2 Toasts
  • 2 Buttons
What we will do ?
-> We will display a long timed Toast when we will click on a button and a short timed when clicked on another button.

Step 1 : Make an android application Project with any name say ToastDemo.
file new

Step 2 : Drag a button in activity_main.xml layout found in res->layout from the Palette.
The code for activity_main.xml is given below.
drag buttons
activity_main.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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="69dp"
        android:layout_marginTop="68dp"
        android:text="Long timed toast" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="40dp"
        android:text="Short timed toast" />

</RelativeLayout>

Step 3 : Select MainActivity.java from src folder. Write the below code in the file.

MainActivity.java
package com.mia.toastdemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    Button b1;
    Button b2;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        b1 = (Button) findViewById(R.id.button1);
        b2 = (Button) findViewById(R.id.button2);
       
b1.setOnClickListener(new OnClickListener() {
           
            public void onClick(View v) {
               
        Toast.makeText(getApplicationContext(), "long timed message", Toast.LENGTH_LONG).show();
    }
           
});

b2.setOnClickListener(new OnClickListener() {
   
    public void onClick(View v) {
       
Toast.makeText(getApplicationContext(), "short timed message", Toast.LENGTH_SHORT).show();
}
   
});
    }
}

Step 4 : Run the Project (Click on a Button and Toast will appear).
long toastshort toast

Github download
Stay Tuned with Made In Android

Published By:
Yatin Kode
on 11.12.14

28 November 2014

Interview Questions & Answers on Android.

1. What is Android?
Android is a stack of software for mobile device which includes an Operating System, middleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine. Many Virtual Machines run efficiently by a DVM device. DVM executes Java languages byte code which later transforms into .dex format files.
2.  What Is the Google Android SDK?

The Google Android SDK is a toolset that developers need in order to write apps on Android enabled devices. It contains a graphical interface that emulates an Android driven handheld environment, allowing them to test and debug their codes.
2. What are the advantages of Android?
  • It is simple and powerful SDK.
  • Licensing, Distribution or Development fee is not required.
  • Easy to Import third party Java library.
  • Supporting platforms are – Linux, Mac Os, Windows.
  • Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities in Android.
  • Components can be reused and replaced by the application framework.
  • Optimized DVM for mobile devices.
  • SQLite enables to store the data in a structured manner.
  • Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies.
  • The development is a combination of a device emulator, debugging tools, memory profiling and plug-in for Eclipse IDE.
- See more at: http://madeinandroid.blogspot.in/2014/11/interview-questions-answers-on-android.html#sthash.YxT1LCiv.dpuf
2. What are the advantages of Android?
  • It is simple and powerful SDK.
  • Licensing, Distribution or Development fee is not required.
  • Easy to Import third party Java library.
  • Supporting platforms are – Linux, Mac Os, Windows.
  • Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities in Android.
  • Components can be reused and replaced by the application framework.
  • Optimized DVM for mobile devices.
  • SQLite enables to store the data in a structured manner.
  • Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies.
  • The development is a combination of a device emulator, debugging tools, memory profiling and plug-in for Eclipse IDE.
- See more at: http://madeinandroid.blogspot.in/2014/11/interview-questions-answers-on-android.html#sthash.YxT1LCiv.dpuf
3. What are the different phases of the Activity life cycle?
As an activity transitions from state to state, it is notified of the change by calls to the following protected methods:
1) void onCreate(Bundle savedInstanceState)
2) void onStart()
3) void onRestart()
4) void onResume()
5) void onPause()
6) void onStop()
7) void onDestroy()    Click for more
4. What is intent?
A class (Intent) describes what a caller desires to do. The caller sends this intent to Android’s intent resolver, which finds the most suitable activity for the intent. E.g. opening a PDF file is an intent, and the Adobe Reader is the suitable activity for this intent.
5. What is an AndroidManifest file?
Applications declare their components in a manifest file that's bundled into the Android package, the .apk file that also holds the application's code, files, and resources. The manifest is a structured XML file and is always named AndroidManifest.xml for all applications. It is also used for naming any libraries the application needs to be linked against (besides the default Android library) and identifying any permission the application expects to be granted.
6. What is Dalvik Virtual Machine?
The name of Android's virtual machine. The Dalvik VM is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format using the included "dx" tool. The VM runs on top of Posix-compliant operating systems, which it relies on for underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development base for those used to programming with Java Standard Edition, but it is geared specifically to the needs of a small mobile device.
7. Explain Android Architecture

Click Here 

8. What are the core building blocks of android?

The core building blocks of android are:

  • Activity
  • View
  • Intent
  • Service
  • Content Provider
  • Fragment etc.
9. What items are important in every Android project?  

These are the essential items that are present each time an Android project is created:
- AndroidManifest.xml
- build.xml
- bin/
- src/
- res/
- assets/
10. What is the importance of XML-based layouts?
 
The use of XML-based layouts provides a consistent and somewhat standard means of setting GUI definition format. In common practice, layout details are placed in XML files while other items are placed in source files.

Stay Tuned with Made In Android 

Published By:
Yatin Kode
on 28.11.14

26 November 2014

The BlueStacks Android mobile emulator

Here we will get to know about using the BlueStacks Emulator.

Step 1 : Download the Bluestacks emulator by following the video below :

Step 2 : You can run your apk of your own project directly from the Bluestacks emulator. Go to the folder where the apk is stored.
"workspace/Project/bin/"

Lets run the project we had made in our previous post "Make A Spinner or a drop-down list"and go to the link in the pic below. Then double-click the .apk file with BlueStacks logo.

bluestacks run

Step 3 : The app will be directly installed on bluestacks . Click on My Apps and then on the app you installed (SpinnerDemo).
inside bluestacks


Step 4 : The App in running state.
running app
Stay Tuned with Made In Android

Published By:
Yatin Kode
on 26.11.14

Previous Page Next Page Home
Top