Monday, September 10, 2012

Android | TabView

Below is source code of how to implement TabView in Android.

Note: It has been verified in Android emulator 4.0.3.

activity_tab_example.xml


<TabHost 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:id="@android:id/tabhost" >
   
    <LinearLayout
        android:id="@+id/tablinearlayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
       
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </TabWidget>

       
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            ></FrameLayout>
    </LinearLayout>


   
</TabHost>

strings.xml

<resources>

    <string name="app_name">TabExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_tab_example">Tab Example</string>
    <string name="title_activity_plus_tab">PlusTabActivity</string>
    <string name="title_activity_minus_tab">MinusTabActivity</string>
    <string name="title_activity_multiplication_tab">MultiplicationTabActivity</string>
    <string name="title_activity_division_tab">DivisionTabActivity</string>
    <string name="plus">You clicked on Plus.</string>
    <string name="minus">You clicked on Minus.</string>
    <string name="division">You clicked on Division.</string>
    <string name="multiplication">You clicked on Multiplication.</string>

</resources>

TabExample.java

package com.example.tabexample;

import android.os.Bundle;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.util.Log;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

@SuppressWarnings("deprecation")
public class TabExample extends TabActivity {

private TabHost oTabHost;
    @SuppressWarnings("null")
@Override
    public void onCreate(Bundle savedInstanceState) {
        
    try
    {
    super.onCreate(savedInstanceState);
       
      
       setContentView(R.layout.activity_tab_example);
       
       oTabHost = (TabHost) findViewById(android.R.id.tabhost);
       
       oTabHost = getTabHost();
       
       TabHost.TabSpec oTabSpec1 ;
       oTabSpec1 = oTabHost.newTabSpec("+");
       oTabSpec1.setIndicator("+", getResources().getDrawable(R.drawable.sq_plus));
       Intent oPlusIntent = new Intent(this, PlusTabActivity.class);
       oTabSpec1.setContent(oPlusIntent);
       oTabHost.addTab(oTabSpec1);
       
       TabHost.TabSpec oTabSpec2 = oTabHost.newTabSpec("-");
       oTabSpec2.setIndicator("-", getResources().getDrawable(R.drawable.sq_minus));        
       Intent oMinusIntent = new Intent(this, MinusTabActivity.class);
       oTabSpec2.setContent(oMinusIntent);
       oTabHost.addTab(oTabSpec2);
       
       TabHost.TabSpec oTabSpec3 = oTabHost.newTabSpec("*");
       oTabSpec3.setIndicator("*", getResources().getDrawable(R.drawable.multiply));        
       Intent oMultiplicationIntent = new Intent(this, MultiplicationTabActivity.class);
       oTabSpec3.setContent(oMultiplicationIntent);
       oTabHost.addTab(oTabSpec3);
       
       TabHost.TabSpec oTabSpec4 = oTabHost.newTabSpec("/");
       oTabSpec4.setIndicator("/", getResources().getDrawable(R.drawable.sign_direction));
       Intent oDivisionIntent = new Intent(this, DivisionTabActivity.class);
       oTabSpec4.setContent(oDivisionIntent);
       oTabHost.addTab(oTabSpec4);
    }
    catch(Exception e){
    Log.d("TabExample", e.getMessage());
    }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_tab_example, menu);
        return true;
    }
}


Snapshot of application structure. I have added 4 layout files and 4 images files in drawable folder.





Result:

In below example, you will get only text in each tab. if you want images then you need to keep first parameter of setIndicator method of each tab blank.


Tuesday, September 4, 2012

Android | DialogBox Example

Here, i would like to show you how we can show confirmation dialog box.

Note: below code has been verified on Android Emulator 4.0.3.

Code: activity_dialog_example.xml




<LinearLayout 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:orientation="vertical" >


    <Button
        android:id="@+id/btnyesno"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btnyesno"/>

    <Button
        android:id="@+id/btnitems"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btnitems"/>
 
    <Button
        android:id="@+id/btnsingleitem"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btnsingleitem"/>
     
</LinearLayout>


Code: strings.xml


<resources>

    <string name="app_name">DialogExample</string>

    <string name="menu_settings">Settings</string>
    <string name="title_activity_dialog_example">Dialog Example</string>

    <string name="btnyesno">Yes or No</string>
    <string name="deletedialog">Confirmation</string>
    <string name="deletemessage">Are you sure, Do you want to exit ?</string>
 
    <string name="btnitems">Items</string>
    <string name="btnsingleitem">Single Item Selection</string>
</resources>

Code:DialogExample.java


package com.example.dialogexample;

import javax.crypto.spec.OAEPParameterSpec;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;



public class DialogExample extends Activity implements OnClickListener {

static final int YESORNO_DIALOG = 1;
static final int IITEMS_DIALOG = 2;
static final int SINGLEITEMSELECTION_DIALOG = 3;

Button btnYesNo, btnItems, btnSingleItem;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog_example);
     
        btnYesNo = (Button) findViewById(R.id.btnyesno);
        btnYesNo.setOnClickListener(this);
     
        btnItems = (Button) findViewById(R.id.btnitems);
        btnItems.setOnClickListener(this);
     
        btnSingleItem = (Button) findViewById(R.id.btnsingleitem);
        btnSingleItem.setOnClickListener(this);
     
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_dialog_example, menu);
        return true;
    }

    @Override
    @Deprecated
    protected Dialog onCreateDialog(int id) {
    // TODO Auto-generated method stub
AlertDialog.Builder oAlert = new Builder(this);     //Here "this" is must if we use "getApplicationContext" then shows an error.
AlertDialog oDialog = (AlertDialog)  super.onCreateDialog(id);

    try
    {

    switch (id){
    case DialogExample.YESORNO_DIALOG:

    oAlert.setMessage(R.string.deletemessage);
    oAlert.setTitle(R.string.deletedialog);
    oAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
   
    public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub
    DialogExample.this.finish();
    }
    });
   
    oAlert.setNegativeButton("No", new DialogInterface.OnClickListener() {
   
    public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub
    arg0.cancel();
    }
    });
   
    oDialog = oAlert.create();
    break;
    case IITEMS_DIALOG:
final String[] strColor = {"Red","Green","Blue"};
oAlert.setTitle("Colors");

oAlert.setItems(strColor, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), strColor[arg1].toString(), Toast.LENGTH_LONG).show();
}
});
oDialog = oAlert.create();
break;

    case SINGLEITEMSELECTION_DIALOG:
    final String[] strFruit = {"Apple","Grapes","Mango"};
    oAlert.setTitle("Fruits");
    oAlert.setSingleChoiceItems(strFruit, -1, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), strFruit[arg1].toString(), Toast.LENGTH_LONG).show();

}
});
    oDialog = oAlert.create();
    break;
    }

   }
    catch(Exception e){
    Log.d("Dialogbox",e.getMessage().toString());
   
    }
    return oDialog;
    }

public void onClick(View arg0) {
// TODO Auto-generated method stub
try{

switch(arg0.getId()){
case R.id.btnyesno:
showDialog(YESORNO_DIALOG);
break;
case R.id.btnitems:
showDialog(IITEMS_DIALOG);
break;
case R.id.btnsingleitem:
showDialog(SINGLEITEMSELECTION_DIALOG);
break;

}
}
catch(Exception e){
Log.d("Dialogbox",e.getMessage().toString());
}
}
}



Result of Clicking on "Yes or No" button :




Note: 
As per the code, when user selects "Yes" then application will be closed and nothing will happen when user selects "No".
Result of while user clicks on "Items" button


Result of while user clicks on "Select Single item".






Wednesday, August 29, 2012

Android | Intent Example of Explicit

As everyone knows, Android application might have more than one screen (activity). It is needed to pass some or all of the values from one activity to another activity. to achieve this, we have intent.

Intent and intent-filters are important component in Android platform.

There are two type of Intent (1) Explicit and (2) Implicit.

Explicit intent, in which target activity is already mentioned in the code. whereas, in Implicit Intent, it is decided run time through Intent-Filters.

Below is code, it explains you how Explicit intent will work. For that we need two activities. here i have added two activities with below names in the application.
(1) IntentExample (calling activity)
(2) Intent_1Example (to be called by IntentExample activity)

activity_intent_example.xml


<LinearLayout 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:orientation="vertical" >

    <TextView
        android:id="@+id/tvfirstname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvfirstname"
        />
<EditText
   android:id="@+id/etfirstname"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:text="@string/etfirstname"
   android:inputType="text"
   />
    <TextView
        android:id="@+id/tvlastname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvlastname"
        />  
       
<EditText
   android:id="@+id/etlastname"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:text="@string/etlastname"
   android:inputType="text"
   />

<Button
   android:id="@+id/btnok"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/btnok"
   />
</LinearLayout>

strings.xml

<resources>

    <string name="app_name">IntentExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_intent_example">Intent Example</string>
    <string name="tvfirstname">First Name:</string>
    <string name="tvlastname">Last Name:</string>
    <string name="etfirstname"></string>
    <string name="etlastname"></string>
    <string name="btnok">OK</string>
    <string name="hello_world">Hello world!</string>
    <string name="title_activity_intent_1_example">Intent_1Example</string>
<string name="tvfirstname1"></string>
<string name="tvlastname1"></string>
</resources>


IntentExample.java

package com.example.intentexample;

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

public class IntentExample extends Activity implements OnClickListener {

private Button btnOk;
private EditText etFirstName, etLastName;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_example);
        
        btnOk = (Button) findViewById(R.id.btnok);
        etFirstName=(EditText) findViewById(R.id.etfirstname);
        etLastName= (EditText) findViewById(R.id.etlastname);
        
        btnOk.setOnClickListener(this);
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_intent_example, menu);
        return true;
    }

public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent oIntent = new Intent(this.getApplicationContext(),Intent_1Example.class);
oIntent.putExtra("com.example.intentexample.firstname", etFirstName.getText().toString());
oIntent.putExtra("com.example.intentexample.lastname", etLastName.getText().toString());
startActivity(oIntent);
}
}


In above code, we have passed two values firstname and lastname to Intent_1example activity through intent. but those values are not displayed in Intent_1Example activity.

Below is code which helps you to display the values passed through intent to Intent_1Example activity.

activity_intent_1_example.xml

<LinearLayout 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:orientation="vertical" >

    <TextView
android:id="@+id/tvfirstname1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvfirstname1"
/>
    <TextView
android:id="@+id/tvlastname1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvlastname1"
/>
    
</LinearLayout>


Intent_1Example.java

package com.example.intentexample;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;

public class Intent_1Example extends Activity {

private Intent oIntent;
private TextView tvFirstName, tvLastName;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_1_example);
        
        oIntent = getIntent();
        tvFirstName = (TextView) findViewById(R.id.tvfirstname1);
        tvLastName = (TextView) findViewById(R.id.tvlastname1);
        tvFirstName.setText("FirstName: " + oIntent.getCharSequenceExtra("com.example.intentexample.firstname").toString());
        tvLastName.setText("Last Name : " + oIntent.getCharSequenceExtra("com.example.intentexample.lastname").toString());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_intent_1_example, menu);
        return true;
    }
}

Result:






Tuesday, August 28, 2012

Android | RatingBar Example

Below is an example of Android RatingBar element.

Note: Example is verified with Android 4.0.3 emulator.

activity_rating_bar_example.xml


<LinearLayout 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:orientation="vertical" >

   
    <RatingBar
        android:id="@+id/rbrating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:rating="0"
        android:stepSize=".1"
       />
   
    <TextView
        android:id="@+id/tvratingvalue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvratingvalue"
/>
    <TextView
        android:id="@+id/tvuser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvuser"
/>  

    <Button
        android:id="@+id/btnok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btnok"
/>
</LinearLayout>


strings.xml

<resources>

    <string name="app_name">RatingBarExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_rating_bar_example">RatingBar Example</string>
    
    <string name="tvratingvalue"></string>
    <string name="tvuser"></string>
    <string name="btnok">Set rating at 2.5</string>
</resources>

RatingBarExample.java

package com.example.ratingbarexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;

public class RatingBarExample extends Activity implements OnRatingBarChangeListener, OnClickListener {
private RatingBar rbRatingBar  ;
private TextView tvRatingValue, tvUser;
private Button btnOk;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rating_bar_example);
        
        rbRatingBar = (RatingBar) findViewById(R.id.rbrating);
        tvRatingValue = (TextView) findViewById(R.id.tvratingvalue);
        tvUser = (TextView) findViewById(R.id.tvuser);
        btnOk  = (Button) findViewById(R.id.btnok);
        
        rbRatingBar.setOnRatingBarChangeListener(this);
        btnOk.setOnClickListener(this);
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_rating_bar_example, menu);
        return true;
    }

public void onRatingChanged(RatingBar arg0, float arg1, boolean arg2) {
// TODO Auto-generated method stub
tvRatingValue.setText("Rating : " + String.valueOf(arg1));
if (arg2 == true)
tvUser.setText("Changed by User"); //shows when user do by himself/herself
else
tvUser.setText("Changed by function"); // when set by function like clicking on Button
}

public void onClick(View arg0) {
// TODO Auto-generated method stub
rbRatingBar.setProgress(25);
}
}

Result:


Android | ImageView Example

Imageview used to display image.

Note: Below code is verified with Android 4.0.3 emulator.

activity_image_view_example.xml


<LinearLayout 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:orientation="vertical" >

    <ImageView
        android:id="@+id/ivfirst"
        android:layout_height="match_parent"
        android:layout_width ="match_parent"
        android:src="@drawable/ic_launcher"
        android:contentDescription="@string/ivfirst"
        />
</LinearLayout>

strings.xml


<LinearLayout 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:orientation="vertical" >

    <ImageView
        android:id="@+id/ivfirst"
        android:layout_height="match_parent"
        android:layout_width ="match_parent"
        android:src="@drawable/ic_launcher"
        android:contentDescription="@string/ivfirst"
        />
</LinearLayout>

ImageViewExample.java


package com.example.testexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class ImageViewExample extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_view_example);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_image_view_example, menu);
        return true;
    }
}


Result:




Android | Spinner Example

When we have multiple values and out of them we need to select one item then we can use Spinner UI component.

Populating Spinner is little bit different. I would like to guide you that there are two sources from which we can populate spinner (1) Array and (2) database.

Adapter is playing key role between UI component and data sources.

Note: below example verified on Android 4.0.3 emulator.

activity_spinner_example.xml


<LinearLayout 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:orientation="vertical" >
   
    <Spinner
        android:id="@+id/spnrcountries"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />


</LinearLayout>


Strings.xml


<resources>

    <string name="app_name">SpinnerExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_spinner_example">Spinner Example</string>
   
   
</resources>

SpinnerExample.java



package com.example.spinnerexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class SpinnerExample extends Activity  {

private Spinner spnrCountries;
private String[] strCountries = {"US","UK","Spain","Germany","Italy","India","China"};

private ArrayAdapter<String> oArrayAdapter ;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_example);
       

        spnrCountries = (Spinner) findViewById(R.id.spnrcountries);
       

        oArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, strCountries);
        spnrCountries.setAdapter(oArrayAdapter);
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_spinner_example, menu);
        return true;
    }


}


Result:




Android | Toast Example

In most of the applications, we need to show messages like "Data save successfully.", "Delete successfully.". To show such type of message, android provides "Toast" feature.

Note: verified on Android 4.0.3 Emulator.


Below code will help you get above toast message.

Code of Layout file:


<LinearLayout 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:orientation="vertical" >

    <Button
        android:id="@+id/btnok"
        android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btnok" />
</LinearLayout>

Code of Strings.xml file:


<resources>

    <string name="app_name">ToastExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_toast_example">Toast Example</string>

    <string name="btnok">OK</string>
</resources>



Code of Java file:


package com.example.toastexample;

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

public class ToastExample extends Activity implements OnClickListener {

private Button btnOk;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toast_example);
       
        btnOk = (Button) findViewById(R.id.btnok);
       
        btnOk.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_toast_example, menu);
        return true;
    }

public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Hi Friends !!" , Toast.LENGTH_LONG).show();

}
}


Above, code always displays message at default location. Now, if you want to set toast at your desired location (like center of screen) then replace above "OnClick" method with below one in "Java" file.

public void onClick(View arg0) {
// TODO Auto-generated method stub
try{
Toast oToast = Toast.makeText(getApplicationContext(), "Hi Friends!!", Toast.LENGTH_LONG);
oToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
oToast.show();
}
catch(Exception e){
Log.e("Toast App", e.getMessage());
}


Result:


Now, it is time to design own screen for Toast.

activity_toast_example.xml:

<LinearLayout 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:orientation="vertical" >

    <Button 
        android:id="@+id/btnok"
        android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btnok" />
</LinearLayout>

toast_layout.xml (Create this file in layout folder and add an image in each drawable folder)

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tbllayouttoast"
    android:background="#bbff0000"
     >
    <TableRow>
        <ImageView 
            android:id="@+id/ivimage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/us"
            android:contentDescription="@string/ivimage"
            android:padding="10dp"
            />
        <TextView
            android:id="@+id/tvimage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="@string/tvimage"
            android:padding="10dp"
            android:textColor="#FFFFFFFF"
            />
    </TableRow>
</TableLayout>

Strings.xml

<resources>

    <string name="app_name">ToastExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_toast_example">Toast Example</string>

    <string name="btnok">OK</string>
    <string name="ivimage"></string>
    <string name="tvimage">Hi Friends !!</string>
</resources>

ToastExample.java

package com.example.toastexample;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class ToastExample extends Activity implements OnClickListener {
private Button btnOk;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toast_example);
        
        btnOk = (Button) findViewById(R.id.btnok);
        
        btnOk.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_toast_example, menu);
        return true;
    }

public void onClick(View arg0) {
// TODO Auto-generated method stub
try{
LayoutInflater oLayoutInflater = getLayoutInflater();
View oView = oLayoutInflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.tbllayouttoast));
Toast oToast = new Toast(getApplicationContext());
oToast.setDuration(Toast.LENGTH_LONG);
oToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
oToast.setView(oView);
oToast.show();

}
catch(Exception e){
Log.e("Toast App", e.getMessage());
}
}

}


Result:






Monday, August 27, 2012

Android | SeekBar with new look

When i am using Seekbar in Android 4.0.3 emulator. the look of it does not attract people. so i decided to play with its look and below is sample code through which you can apply your own look to Seekbar.

As everyone knows, Seekbar consists of progress line and progress thumb. Here we will override existing look with new ones and we will get what we want.

Note: It has been verified on Android 4.0.3 emulator.

Below are steps:


  • Create folder called "drawable" in "res" folder.
  • Add "seekbar_line.xml" file by right click on "drawable" folder -> New -> Android XML file -> give file name and then select "Shape" from given list and then follow steps.
  • Add below code to "seekbar_line.xml" file.


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:visible="true"
android:shape="line" >
<stroke android:width="1dp"  android:color="#FF000000" />
</shape>


  • then add another file with "seekbar_thumb.xml" name and then add below code to it.


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:visible="true"
android:dither="true">

    <size
        android:width="10dp"
        android:height="20dp"/>
   
    <corners
        android:radius="2dp" />
   
    <gradient
        android:startColor="#FFAA0000"
        android:endColor="#FFFF0000"
        android:angle="0"
        android:type="linear"
        />
   

</shape>



Code of Strings.xml file:


<resources>

    <string name="app_name">SeekBarExample</string>
    <string name="tvvalue"></string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_seek_bar_example">SeekBar Example</string>

</resources>


Code of Layout file:


<LinearLayout 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:orientation="vertical" >

    <TextView
        android:id="@+id/tvvalue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvvalue"
/>
   
    <SeekBar
        android:id="@+id/sbvalue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="99"
        android:progress="0"
        android:thumb="@drawable/seekbar_thumb"
        android:thumbOffset="0dp"
        android:progressDrawable="@drawable/seekbar_line"
        />

</LinearLayout>


Code of Java file:


package com.example.seekbarexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class SeekBarExample extends Activity implements OnSeekBarChangeListener {

private TextView tvValue;
private SeekBar sbValue;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seek_bar_example);
       
        tvValue = (TextView) findViewById(R.id.tvvalue);
        sbValue = (SeekBar) findViewById(R.id.sbvalue);
       
        sbValue.setOnSeekBarChangeListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_seek_bar_example, menu);
        return true;
    }

public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub

tvValue.setText(String.valueOf(arg1));


}

public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub

}

public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub

}
}


Result:






Android | Seekbar | Color Maker

This is another example of Seekbar. i used it to develop color maker.

As you know, color is combination of 4 elements, Alpha, Red, Green and Blue. Alpha is used to set value between transparency and opaque states.

I have verified the code in Android 4.0.3 emulator.

Code of Layout File:


<LinearLayout 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:orientation="vertical"
    android:id="@+id/llcolormaker" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvalphacolor"
        android:textColor="#FFFFFFFF"
        />  

    <SeekBar
        android:id="@+id/sbalpha"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255"  />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvredcolor"
        android:textColor="#FFFFFFFF"
        />

    <SeekBar
        android:id="@+id/sbred"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="0"  />
       
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvgreencolor"
        android:textColor="#FFFFFFFF"
        />

    <SeekBar
        android:id="@+id/sbgreen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="0"  />  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvbluecolor"
        android:textColor="#FFFFFFFF"
        />

    <SeekBar
        android:id="@+id/sbblue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="0"  />  
</LinearLayout>

Code of Strings.xml file:


<resources>

    <string name="app_name">ColorMakerExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_color_maker_example">Color Maker Example</string>

    <string name="tvalphacolor">Select Alpha :</string>
    <string name="tvredcolor">Select Red Color :</string>
    <string name="tvgreencolor">Select Green Color :</string>
    <string name="tvbluecolor">Select Blue Color :</string>
</resources>

code of Java file:



package com.example.colormakerexample;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class ColorMakerExample extends Activity implements OnSeekBarChangeListener {

SeekBar sbAlpha, sbRed, sbGreen, sbBlue;
LinearLayout llColorMaker;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color_maker_example);
       
        sbAlpha = (SeekBar) findViewById(R.id.sbalpha);
        sbRed = (SeekBar) findViewById(R.id.sbred);
        sbGreen = (SeekBar) findViewById(R.id.sbgreen);
        sbBlue = (SeekBar) findViewById(R.id.sbblue);
        llColorMaker = (LinearLayout) findViewById(R.id.llcolormaker);
       
        sbAlpha.setOnSeekBarChangeListener(this);
        sbRed.setOnSeekBarChangeListener(this);
        sbGreen.setOnSeekBarChangeListener(this);
        sbBlue.setOnSeekBarChangeListener(this);
       

        llColorMaker.setBackgroundColor(Color.argb(sbAlpha.getProgress(), sbRed.getProgress(), sbGreen.getProgress(), sbBlue.getProgress()));
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_color_maker_example, menu);
        return true;
    }


public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub

        llColorMaker.setBackgroundColor(Color.argb(sbAlpha.getProgress(), sbRed.getProgress(), sbGreen.getProgress(), sbBlue.getProgress()));

}


public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub

}

public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub

}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
sbAlpha = sbRed = sbGreen = sbBlue = null;
super.onDestroy();
}
}



Result:




Android | Seekbar Example

Seekbar is widget and we can use to select the value from selected range.

max property will set the max value for seekbar and progress property will give the current value of where seekbar positioned. ensure, seekbar starts with "0".

below is example of Seekbar which i have verified on Android 4.0.3 emulator.

Code of Layout File:


<LinearLayout 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:orientation="vertical" >

    <TextView
        android:id="@+id/tvvalue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvvalue"
/>
   
    <SeekBar
        android:id="@+id/sbvalue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="99"
        android:progress="0"/>

</LinearLayout>

Code of Strings.xml File:


<resources>

    <string name="app_name">SeekBarExample</string>
    <string name="tvvalue"></string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_seek_bar_example">SeekBar Example</string>

</resources>


Source code of .JAVA file:


package com.example.seekbarexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class SeekBarExample extends Activity implements OnSeekBarChangeListener {

private TextView tvValue;
private SeekBar sbValue;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seek_bar_example);
       
        tvValue = (TextView) findViewById(R.id.tvvalue);
        sbValue = (SeekBar) findViewById(R.id.sbvalue);
       
        sbValue.setOnSeekBarChangeListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_seek_bar_example, menu);
        return true;
    }

public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub

tvValue.setText(String.valueOf(arg1));


}

public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub

}

public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub

}
}

Result: