Showing posts with label android tutorials. Show all posts
Showing posts with label android tutorials. Show all posts

Monday, November 16, 2015

Words- Characters Counter Android Demo



Description:

It is very easy to handle words and characters counter for your application. If you are developing an app which uses EditText, It is very important to give feature like word counter / Character counter within the app. Here is the full demo code which helps you.

First add below code to your activity_main.xml file.


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="0.4"
    android:orientation="vertical"
    android:paddingLeft="5dip"
    android:paddingRight="5dip" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:paddingBottom="10dp" >

        <TextView
            android:id="@+id/tvCharWatcher"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:textSize="22dp"
            android:text="Characters:" />

        <TextView
            android:id="@+id/tvWordWatcher"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerInParent="true"
            android:textSize="22dp"
            android:text="Words:" />
    </RelativeLayout>

    <EditText
        android:id="@+id/note"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:autoText="false"
        android:background="@android:color/white"
        android:capitalize="none"
        android:ems="10"
        android:fadingEdge="none"
        android:gravity="top"
        android:scrollbars="vertical|horizontal"
        android:textColor="@android:color/black"
        android:textSize="22dp" >

        <requestFocus />
    </EditText>

</LinearLayout>


Your layout is ready, now you need to register components to MainActivity.java file and add below code step by step:

1. Create method init() to initialize needful variables,components etc.
2. TextWatcher class handles your EditText and it will call with every text you add.
3. WordCount() custom method counts words and return number of words.

Here, is the full code of MainActivity.java file

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

EditText etText;
TextView tvWordWatcher, tvCharWatcher;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

init();
}

private void init() {

etText = (EditText) findViewById(R.id.note);
etText.setVerticalScrollBarEnabled(true);
etText.requestFocus();

tvCharWatcher = (TextView) findViewById(R.id.tvCharWatcher);
tvWordWatcher = (TextView) findViewById(R.id.tvWordWatcher);
tvCharWatcher.setText("Characters:0");
tvWordWatcher.setText("Words:0");

etText.addTextChangedListener(textWatcher);
}

TextWatcher textWatcher = new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
tvCharWatcher.setText("Characters:"
+ String.valueOf(s.length()));
tvWordWatcher.setText("Words:" + wordcount(s.toString()));
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {

}

@Override
public void afterTextChanged(Editable s) {

}
};

public static long wordcount(String line) {
long numWords = 0;
int index = 0;
boolean prevWhiteSpace = true;
while (index < line.length()) {
char c = line.charAt(index++);
boolean currWhiteSpace = Character.isWhitespace(c);
if (prevWhiteSpace && !currWhiteSpace) {
numWords++;
}
prevWhiteSpace = currWhiteSpace;
}
return numWords;
}
}


Download Full Source Code: GitHub


Wednesday, September 25, 2013

ListView with Checkbox android example



Download Full Source Code : Source Code



  • Create new project named "ListviewWithCheckbox".
  • add following code in activity_main.xml file.

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffeeeeee"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Country Codes"
        android:textSize="20sp" />

    <Button
        android:id="@+id/findSelected"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get Selected Items" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>


  • Add below code in MainActivity.java file.

MainActivity.java



public class MainActivity extends Activity {

MyCustomAdapter dataAdapter = null;

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

// Generate list View from ArrayList
displayListView();

checkButtonClick();

}

private void displayListView() {

// Array list of countries
ArrayList<States> stateList = new ArrayList<States>();

States _states = new States("91", "India", false);
stateList.add(_states);
_states = new States("61", "Australia", true);
stateList.add(_states);
_states = new States("55", "Brazil", false);
stateList.add(_states);
_states = new States("86", "China", true);
stateList.add(_states);
_states = new States("49", "Germany", true);
stateList.add(_states);
_states = new States("36", "Hungary", false);
stateList.add(_states);
_states = new States("39", "Italy", false);
stateList.add(_states);
_states = new States("1", "US", false);
stateList.add(_states);
_states = new States("44", "UK", false);
stateList.add(_states);

// create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this, R.layout.state_info, stateList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);

listView.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
States state = (States) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Clicked on : " + state.getName(), Toast.LENGTH_LONG)
.show();
}
});
}

private class MyCustomAdapter extends ArrayAdapter<States> {

private ArrayList<States> stateList;

public MyCustomAdapter(Context context, int textViewResourceId,

ArrayList<States> stateList) {
super(context, textViewResourceId, stateList);
this.stateList = new ArrayList<States>();
this.stateList.addAll(stateList);
}

private class ViewHolder {
TextView code;
CheckBox name;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder = null;

Log.v("ConvertView", String.valueOf(position));

if (convertView == null) {

LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

convertView = vi.inflate(R.layout.state_info, null);

holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView
.findViewById(R.id.checkBox1);

convertView.setTag(holder);

holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
States _state = (States) cb.getTag();

Toast.makeText(
getApplicationContext(),
"Checkbox: " + cb.getText() + " -> "
+ cb.isChecked(), Toast.LENGTH_LONG)
.show();

_state.setSelected(cb.isChecked());
}
});

} else {
holder = (ViewHolder) convertView.getTag();
}

States state = stateList.get(position);

holder.code.setText(" (" + state.getCode() + ")");
holder.name.setText(state.getName());
holder.name.setChecked(state.isSelected());

holder.name.setTag(state);

return convertView;
}

}

private void checkButtonClick() {

Button myButton = (Button) findViewById(R.id.findSelected);

myButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

StringBuffer responseText = new StringBuffer();
responseText.append("Selected Countries are...\n");

ArrayList<States> stateList = dataAdapter.stateList;

for (int i = 0; i < stateList.size(); i++) {
States state = stateList.get(i);

if (state.isSelected()) {
responseText.append("\n" + state.getName());
}
}

Toast.makeText(getApplicationContext(), responseText,
Toast.LENGTH_LONG).show();
}
});
}

}



  • Create new POJO java class,Which is used for getters and setters methods.Named it States.java. 

States.java



public class States {

String code = null;
String name = null;
boolean selected = false;

public States(String code, String name, boolean selected) {
super();
this.code = code;
this.name = name;
this.selected = selected;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public boolean isSelected() {
return selected;
}

public void setSelected(boolean selected) {
this.selected = selected;
}

}

  • Create new XML layout file, which is used to integrate CheckBox and TextView in ListView.Named it state_info.xml.

state_info.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="6dip" >

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="checkbox"
        android:textColor="#B40404" />

    <TextView
        android:id="@+id/code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/checkBox1"
        android:layout_alignBottom="@id/checkBox1"
        android:layout_toRightOf="@id/checkBox1"
        android:text="textview"
        android:textColor="#ff000000" />

</RelativeLayout>


  • Done ! Now run the project.


Download Full Source Code : Source Code



Monday, September 9, 2013

ShakeListener Example

Android device has advance function,It has hardware to detect shake event.It can also detect the direction of shaking device.This advance function measure the value of X, Y and Z direction.Screenshot of Shake Listener is given below.

How to Develop ?

  • Create one Project named "ShakeListener".
  • Insert below code in activity_main.xml file which is stored in res/layout directory of project folder.

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

        <TableLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:stretchColumns="0|1">
        
                <TableRow>
                
                        <TextView
                                android:text="X :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/x"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="Y :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/y"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="Z :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/z"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="aX :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/ax"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="aY :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/ay"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="aZ"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/az"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
                
        </TableLayout>

</LinearLayout>



  • Now Open MainActivity.java file and insert Following code in it.

MainActivity.java

public class MainActivity extends Activity implements SensorEventListener {
    
        SensorManager sensorManager = null;
    private TextView x, y, z, ax, ay, az;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        setContentView(R.layout.activity_main);
        // initialize display
        x = (TextView) findViewById(R.id.x);
        y = (TextView) findViewById(R.id.y);
        z = (TextView) findViewById(R.id.z);
        ax = (TextView) findViewById(R.id.ax);
        ay = (TextView) findViewById(R.id.ay);
        az = (TextView) findViewById(R.id.az);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ORIENTATION),
                SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_GAME);
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        sensorManager.unregisterListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ORIENTATION));
        sensorManager.unregisterListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER));
    }
    
        public void onAccuracyChanged(Sensor sensor, int accuracy) {}
        
        public void onSensorChanged(SensorEvent event) {
                synchronized (this) {
                switch (event.sensor.getType()) {
                        case SensorManager.SENSOR_ORIENTATION :
                                x.setText(String.valueOf(event.values[SensorManager.DATA_X]));
                                y.setText(String.valueOf(event.values[SensorManager.DATA_Y]));
                                z.setText(String.valueOf(event.values[SensorManager.DATA_Z]));
                                break;
                        case SensorManager.SENSOR_ACCELEROMETER :
                                ax.setText(String.valueOf(event.values[SensorManager.DATA_X]));
                                ay.setText(String.valueOf(event.values[SensorManager.DATA_Y]));
                                az.setText(String.valueOf(event.values[SensorManager.DATA_Z]));
                                break;
                }           
        }
        } 
        
}


  • If you get few errors then press CTRL+SHIFT+O. It imports all missing libraries.
  • That's It. Now run the project.

Get Full Source Code: FREE




Sunday, September 1, 2013

GridView Example


GridView is a 2 - Dimensional display of your content. It is mainly useful to show icons or images.
Take a look of GridView.



Example:
  • First Create project named "GridView_Example".
  • Download some images/photos you would like to set in GridView and save it in res/drawable/ directory.
  • Open activity_main.xml file and add following code:

activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>


  • Open the MainActivity.java file and add following code:

MainActivity.java



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

   GridView gridview = (GridView) findViewById(R.id.gridview);
   gridview.setAdapter(new ImageAdapter(this));

   gridview.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
       {
           Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
       }
   });
}


  • Now You get some error in MainActivity.java file,but ignore it.Create New Class file (File - New - Class) named it ImageAdapter.java.
  • Insert following code in ImageAdapter.java file. 

ImageAdapter.java



public class ImageAdapter extends BaseAdapter
{
private Context mContext;

    public ImageAdapter(Context c) 
    {
        mContext = c;
    }

    public int getCount() 
    {
        return mThumbIds.length;
    }

    public Object getItem(int position) 
    {
        return null;
    }

    public long getItemId(int position) 
    {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) 
    {
        ImageView imageView;
        if (convertView == null) 
        {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } 
        else 
        {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

    // references to our images
    private Integer[] mThumbIds = {
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
    };

}

  • Note that, here you have to change names in mThumbIds integer array as per your image names.
  • Done, Now run the project and get output like above image.  


Monday, August 26, 2013

Custom ListView Example

This is a tutorial about customizing listview with and image and text.

Download Source Code for FREE:Here


Creating New Project

  • Create New Project in Eclipse. File => New Project.
  • Create New folder in res named drawable.
  • Create New gradient_bg.xml file in drawable directory and fill with following code. It is used to set gradient background in listView.

gradient_bg.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#424242"
      android:centerColor="#585858"
      android:endColor="#6E6E6E"
      android:angle="270" />
</shape>


  • Create New gradient_bg_hover.xml file in drawable directory and fill with following code. It is used to set gradient background when listView item is pressed.

 gradient_bg_hover.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#8A0808"
      android:centerColor="#610B0B"
      android:endColor="#B40404"
      android:angle="270" />
</shape>

  • Create New list_main.xml file in drawable directory and fill with following code. It is used to integrate above files into listView..

list_main.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
     android:state_selected="false"
        android:state_pressed="false"
        android:drawable="@drawable/gradient_bg" />
    <item android:state_pressed="true"
        android:drawable="@drawable/gradient_bg_hover" />
    <item android:state_selected="true"
     android:state_pressed="false"
        android:drawable="@drawable/gradient_bg_hover" />
</selector>

  • Now add following code into activity_main.xml file.

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#2A0A12"
        android:dividerHeight="2dp"
        android:listSelector="@drawable/list_main" />
</LinearLayout>

  • Next step is to design single row of listView. Create New xml file in layout directory and name it as row_layout.xml.

row_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_main"
    android:orientation="horizontal"
    android:padding="5dip" >


    <LinearLayout
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="5dip"
        android:padding="3dip" >

        <ImageView
            android:id="@+id/list_image"
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>

   

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Country name"
        android:textColor="#FFFFFF"
        android:textSize="15dip"
        android:textStyle="bold"
        android:typeface="sans" />

</RelativeLayout>

  • Until now we completed designing part of the listView. Next step is to add content in listview with different images. Add following code in MainActivity.java file. 

MainActivity.java



public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String listArray[] = new String[] { "India", "England", "Canada",
"New zealand", "South Africa", "Pakistan", "West indies" };
int icon[] = new int[] { R.drawable.india, R.drawable.england,
R.drawable.canada, R.drawable.new_zealand,
R.drawable.south_africa, R.drawable.pakistan,
R.drawable.west_indies };

ListView listView = (ListView) findViewById(R.id.listView);
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();

for (int i = 0; i <= listArray.length - 1; i++) {

HashMap<String, String> hm = new HashMap<String, String>();
hm.put("title", listArray[i]);
hm.put("icon", Integer.toString(icon[i]));
aList.add(hm);
}

String[] sfrm = { "title", "icon" };
int[] sto = { R.id.title, R.id.list_image };

SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList,
R.layout.row_layout, sfrm, sto);

listView.setAdapter(adapter);

listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {

switch (position) {

case 0:
Toast.makeText(getApplicationContext(), "India",
Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "England",
Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "Canada",
Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(getApplicationContext(), "New zealand",
Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(getApplicationContext(), "South Africa",
Toast.LENGTH_SHORT).show();
break;
case 5:
Toast.makeText(getApplicationContext(), "Pakistan",
Toast.LENGTH_SHORT).show();
break;
case 6:
Toast.makeText(getApplicationContext(), "West Indies",
Toast.LENGTH_SHORT).show();
break;

}

}
});
}
}

  • Done !

Download Source Code for FREE:Here



Wednesday, August 21, 2013

Rating Bar Full Example

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    
    <RatingBar android:id="@+id/rating_1"
    android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="3"
        android:rating="2.5">
    </RatingBar>
    
    <RatingBar android:id="@+id/rating_2"
    android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:rating="2.25">
    </RatingBar>
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip">
    
<TextView  
android:id="@+id/rating"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
   
    <RatingBar android:id="@+id/small_ratingbar"
            style="?android:attr/ratingBarStyleSmall"
            android:layout_marginLeft="5dip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical" />
    </LinearLayout>
    
    <RatingBar android:id="@+id/indicator_ratingbar"
        style="?android:attr/ratingBarStyleIndicator"
        android:layout_marginLeft="5dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" 
        />
        
</LinearLayout>



MainActivity.java



public class MainActivity extends Activity implements RatingBar.OnRatingBarChangeListener
{
RatingBar mSmallRatingBar;
RatingBar mIndicatingRatingBar;
TextView mRatingText;
    /** Called when the activity is first created. */
   
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mRatingText=(TextView)findViewById(R.id.rating);
        
        mSmallRatingBar=(RatingBar)findViewById(R.id.small_ratingbar);
        mIndicatingRatingBar=(RatingBar)findViewById(R.id.indicator_ratingbar);
        
        ((RatingBar)findViewById(R.id.rating_1)).setOnRatingBarChangeListener(this);
        ((RatingBar)findViewById(R.id.rating_2)).setOnRatingBarChangeListener(this);
    }
    
   
    public void onRatingChanged(RatingBar ratingBar,float rating,boolean fromTouch)
    {
    final int numStars=ratingBar.getNumStars();
   
    mRatingText.setText(getString(R.string.ratingbar_rating)+" "+rating+" / "+numStars);
   
    if(mIndicatingRatingBar.getNumStars()!=numStars)
    {
    mIndicatingRatingBar.setNumStars(numStars);
    mSmallRatingBar.setNumStars(numStars);
    }
   
    if(mIndicatingRatingBar.getRating()!=rating)
    {
    mIndicatingRatingBar.setRating(rating);
    mSmallRatingBar.setRating(rating);
    }
   
    final float ratingBarStepSize=ratingBar.getStepSize();
   
    if(mIndicatingRatingBar.getStepSize()!=ratingBarStepSize)
    {
    mIndicatingRatingBar.setStepSize(ratingBarStepSize);
    mSmallRatingBar.setStepSize(ratingBarStepSize);
    }
    }

}