May 29, 2011

Create custom dialog using AlertDialog.Builder, with dynamic content

This example have the almost same output in the previous post "Create custom dialog with dynamic content, updated in onPrepareDialog()". The difference is it create dialog using AlertDialog.Builder, instead of in onCreateDialog() and onPrepareDialog().

Create custom dialog using AlertDialog.Builder, with dynamic content

main code, AndroidCaptureScreen.java
package com.AndroidCaptureScreen;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AndroidCaptureScreen extends Activity {
 
 Bitmap bmScreen;
 
 View screen;
 EditText EditTextIn;
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       screen = (View)findViewById(R.id.screen);
       Button btnCaptureScreen = (Button)findViewById(R.id.capturescreen);
       EditTextIn = (EditText)findViewById(R.id.textin);
      
       btnCaptureScreen.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    screen.setDrawingCacheEnabled(true);
    bmScreen = screen.getDrawingCache();
    OpenScreenDialog();
   }});
   }
  
   private void OpenScreenDialog(){
    
    AlertDialog.Builder screenDialog = new AlertDialog.Builder(AndroidCaptureScreen.this);
    screenDialog.setTitle("Captured Screen");
    
    

    TextView TextOut = new TextView(AndroidCaptureScreen.this);
    TextOut.setText(EditTextIn.getText().toString());
    LayoutParams textOutLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    TextOut.setLayoutParams(textOutLayoutParams);
    
    ImageView bmImage = new ImageView(AndroidCaptureScreen.this);
    bmImage.setImageBitmap(bmScreen);
    LayoutParams bmImageLayoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    bmImage.setLayoutParams(bmImageLayoutParams);
    
    LinearLayout dialogLayout = new LinearLayout(AndroidCaptureScreen.this);
    dialogLayout.setOrientation(LinearLayout.VERTICAL);
    dialogLayout.addView(TextOut);
    dialogLayout.addView(bmImage);
    screenDialog.setView(dialogLayout);
       
    screenDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {

         }
        });
    screenDialog.show();
   }

}


main.xml, the main layout of our activity.
<?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"
   android:id="@+id/screen"
   >
<TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   />
<Button
   android:id="@+id/capturescreen"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Capture Screen"
   />
<TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="\nScreen can be captured using: \n\n
screen.setDrawingCacheEnabled(true);\n
bmScreen = screen.getDrawingCache();\n"
   />
<EditText
   android:id="@+id/textin"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
</LinearLayout>


Related Post:
- Create custom dialog using AlertDialog.Builder, by inflating XML


Noted:
- This code capture the first screen only! Read Capture screen with getDrawingCache() repeatly


May 27, 2011

Create custom dialog with dynamic content, updated in onPrepareDialog()

In the post "Create custom dialog with EditText", the dialog is created in onCreateDialog(). Please notice that the call-back function onCreateDialog() will be called when a dialog is requested for the first time, such that the content defined in onCreateDialog() will not be updated next time.

If you have some dynamic content changed in runtime, you can override the call-back method onPrepareDialog(), it will be called every time a dialog is opened. Override this method if you want to change any properties of the dialog each time it is opened.

In this example, we will get dynamic content to the dialog; including the Bitmap by screen capture(refer to the post "Capture Screen, using View.getDrawingCache()"), and the user input from a EditText - both will be changed each time the dialog is opened.

Create custom dialog with dynamic content, updated in onPrepareDialog()

Create /res/layout/screendialog.xml, it's the layout of our dialog
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="10dip"
android:paddingRight="10dip"
>
<TextView
android:id="@+id/textout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:id="@+id/image"
android:layout_width="300px"
android:layout_height="300px"
/>
<Button
android:id="@+id/okdialogbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="OK"
/>
</LinearLayout>


main code, AndroidCaptureScreen.java
package com.AndroidCaptureScreen;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class AndroidCaptureScreen extends Activity {

Bitmap bmScreen;

Dialog screenDialog;
static final int ID_SCREENDIALOG = 1;

ImageView bmImage;
Button btnScreenDialog_OK;
TextView TextOut;

View screen;
EditText EditTextIn;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     screen = (View)findViewById(R.id.screen);
     Button btnCaptureScreen = (Button)findViewById(R.id.capturescreen);
     EditTextIn = (EditText)findViewById(R.id.textin);
  
     btnCaptureScreen.setOnClickListener(new OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   screen.setDrawingCacheEnabled(true);
   bmScreen = screen.getDrawingCache();
   showDialog(ID_SCREENDIALOG);
  }});
 }


@Override
protected Dialog onCreateDialog(int id) {
 // TODO Auto-generated method stub

 screenDialog = null;
 switch(id){
 case(ID_SCREENDIALOG):
  screenDialog = new Dialog(this);
  screenDialog.setContentView(R.layout.screendialog);
  bmImage = (ImageView)screenDialog.findViewById(R.id.image);
  TextOut = (TextView)screenDialog.findViewById(R.id.textout);
  btnScreenDialog_OK = (Button)screenDialog.findViewById(R.id.okdialogbutton);
  btnScreenDialog_OK.setOnClickListener(btnScreenDialog_OKOnClickListener);
 }
 return screenDialog;
}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
 // TODO Auto-generated method stub
 switch(id){
 case(ID_SCREENDIALOG):
  dialog.setTitle("Captured Screen");
  TextOut.setText(EditTextIn.getText().toString());
  bmImage.setImageBitmap(bmScreen);
  break;
 }
}

private Button.OnClickListener btnScreenDialog_OKOnClickListener
 = new Button.OnClickListener(){

 @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  screenDialog.dismiss();
 }};
}


main.xml, the main layout of our activity.
<?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"
 android:id="@+id/screen"
 >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="@string/hello"
 />
<Button
 android:id="@+id/capturescreen"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Capture Screen"
 />
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="\nScreen can be captured using: \n\n
screen.setDrawingCacheEnabled(true);\n
bmScreen = screen.getDrawingCache();\n"
 />
<EditText
 android:id="@+id/textin"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 />
</LinearLayout>


Related:
- Create custom dialog using AlertDialog.Builder, with dynamic content

Noted:
- This code capture the first screen only! Read Capture screen with getDrawingCache() repeatly


May 26, 2011

Capture Screen, using View.getDrawingCache()

To capture screen, such as in a view, we can use the following code:
 View screen = (View)findViewById(R.id.screen);

screen.setDrawingCacheEnabled(true);
Bitmap bmScreen = screen.getDrawingCache();



where screen is the view, to be captured.



it's a working example here: Create custom dialog with dynamic content, updated in onPrepareDialog().

May 25, 2011

Create Options Menu with SurfaceView

To create Options Menu on SurfaceView, simple override onCreateOptionsMenu() to add menu options, and override onOptionsItemSelected() to handle the event.

Create Options Menu with SurfaceView

package com.TestSurefaceView;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;

public class TestSurefaceView extends Activity {

MySurfaceView mySurfaceView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mySurfaceView = new MySurfaceView(this);
setContentView(mySurfaceView);
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mySurfaceView.onResumeMySurfaceView();
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mySurfaceView.onPauseMySurfaceView();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, 0, 0, "Do Something");
menu.add(0, 1, 1, "Do Something Else");
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case 0:
Toast.makeText(TestSurefaceView.this,
"Do Something",
Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(TestSurefaceView.this,
"Do Something Else",
Toast.LENGTH_LONG).show();
break;
}
return true;
}

class MySurfaceView extends SurfaceView implements Runnable{

//In this test, handle maximum of 2 pointer
final int MAX_POINT_CNT = 2;

private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
float[] x = new float[MAX_POINT_CNT];
float[] y = new float[MAX_POINT_CNT];
boolean[] isTouch = new boolean[MAX_POINT_CNT];

float[] x_last = new float[MAX_POINT_CNT];
float[] y_last = new float[MAX_POINT_CNT];
boolean[] isTouch_last = new boolean[MAX_POINT_CNT];


Thread thread = null;
SurfaceHolder surfaceHolder;
volatile boolean running = false;

volatile boolean touched = false;
volatile float touched_x, touched_y;

public MySurfaceView(Context context) {
super(context);
// TODO Auto-generated constructor stub
surfaceHolder = getHolder();

}

public void onResumeMySurfaceView(){
running = true;
thread = new Thread(this);
thread.start();
}

public void onPauseMySurfaceView(){
boolean retry = true;
running = false;
while(retry){
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

@Override
public void run() {
// TODO Auto-generated method stub
while(running){
if(surfaceHolder.getSurface().isValid()){
Canvas canvas = surfaceHolder.lockCanvas();
//... actual drawing on canvas

paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);

if(isTouch[0]){
if(isTouch_last[0]){
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setColor(Color.RED);
canvas.drawLine(x_last[0], y_last[0], x[0], y[0], paint);
}
}
if(isTouch[1]){
if(isTouch_last[1]){
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setColor(Color.BLUE);
canvas.drawLine(x_last[1], y_last[1], x[1], y[1], paint);
}
}

surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}

@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
int pointerIndex = ((motionEvent.getAction() & MotionEvent.ACTION_POINTER_ID_MASK)
>> MotionEvent.ACTION_POINTER_ID_SHIFT);
int pointerId = motionEvent.getPointerId(pointerIndex);
int action = (motionEvent.getAction() & MotionEvent.ACTION_MASK);
int pointCnt = motionEvent.getPointerCount();

if (pointCnt <= MAX_POINT_CNT){
if (pointerIndex <= MAX_POINT_CNT - 1){

for (int i = 0; i < pointCnt; i++) {
int id = motionEvent.getPointerId(i);
x_last[id] = x[id];
y_last[id] = y[id];
isTouch_last[id] = isTouch[id];
x[id] = motionEvent.getX(i);
y[id] = motionEvent.getY(i);
}

switch (action){
case MotionEvent.ACTION_DOWN:
isTouch[pointerId] = true;
break;
case MotionEvent.ACTION_POINTER_DOWN:
isTouch[pointerId] = true;
break;
case MotionEvent.ACTION_MOVE:
isTouch[pointerId] = true;
break;
case MotionEvent.ACTION_UP:
isTouch[pointerId] = false;
isTouch_last[pointerId] = false;
break;
case MotionEvent.ACTION_POINTER_UP:
isTouch[pointerId] = false;
isTouch_last[pointerId] = false;
break;
case MotionEvent.ACTION_CANCEL:
isTouch[pointerId] = false;
isTouch_last[pointerId] = false;
break;
default:
isTouch[pointerId] = false;
isTouch_last[pointerId] = false;
}
}
}

return true;
}

}
}



Related Post:
- Create OptionsMenu in /res/menu/menu.xml
- Create OptionsMenu using menu.add()

May 24, 2011

Detect multi-touch, on SurfaceView

Override onTouchEvent() in SurfaceView to handle mlti-touch.



package com.TestSurefaceView;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class TestSurefaceView extends Activity {
 
 MySurfaceView mySurfaceView;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mySurfaceView = new MySurfaceView(this);
        setContentView(mySurfaceView);
    }
    
    @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  mySurfaceView.onResumeMySurfaceView();
 }

 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  mySurfaceView.onPauseMySurfaceView();
 }

 class MySurfaceView extends SurfaceView implements Runnable{
  
  //In this test, handle maximum of 2 pointer
  final int MAX_POINT_CNT = 2;
  
  private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  float[] x = new float[MAX_POINT_CNT];
  float[] y = new float[MAX_POINT_CNT];
  boolean[] isTouch = new boolean[MAX_POINT_CNT];
  
  float[] x_last = new float[MAX_POINT_CNT];
  float[] y_last = new float[MAX_POINT_CNT];
  boolean[] isTouch_last = new boolean[MAX_POINT_CNT];

     
     Thread thread = null;
     SurfaceHolder surfaceHolder;
     volatile boolean running = false;
     
     volatile boolean touched = false;
     volatile float touched_x, touched_y;

  public MySurfaceView(Context context) {
   super(context);
   // TODO Auto-generated constructor stub
   surfaceHolder = getHolder();

  }
  
  public void onResumeMySurfaceView(){
   running = true;
   thread = new Thread(this);
   thread.start();
  }
  
  public void onPauseMySurfaceView(){
   boolean retry = true;
   running = false;
   while(retry){
    try {
     thread.join();
     retry = false;
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }

  @Override
  public void run() {
   // TODO Auto-generated method stub
   while(running){
    if(surfaceHolder.getSurface().isValid()){
     Canvas canvas = surfaceHolder.lockCanvas();
     //... actual drawing on canvas

     paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(1);
     
     if(isTouch[0]){
      if(isTouch_last[0]){
       paint.setStyle(Paint.Style.STROKE);
          paint.setStrokeWidth(5);
          paint.setColor(Color.RED);
          canvas.drawLine(x_last[0], y_last[0], x[0], y[0], paint);
      }
     }
     if(isTouch[1]){
      if(isTouch_last[1]){
       paint.setStyle(Paint.Style.STROKE);
          paint.setStrokeWidth(5);
          paint.setColor(Color.BLUE);
          canvas.drawLine(x_last[1], y_last[1], x[1], y[1], paint);
      }
     }
     
     surfaceHolder.unlockCanvasAndPost(canvas);
    }
   }
  }

  @Override
  public boolean onTouchEvent(MotionEvent motionEvent) {
   int pointerIndex = ((motionEvent.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) 
     >> MotionEvent.ACTION_POINTER_ID_SHIFT);
   int pointerId = motionEvent.getPointerId(pointerIndex);
   int action = (motionEvent.getAction() & MotionEvent.ACTION_MASK);
   int pointCnt = motionEvent.getPointerCount();
   
   if (pointCnt <= MAX_POINT_CNT){
    if (pointerIndex <= MAX_POINT_CNT - 1){

     for (int i = 0; i < pointCnt; i++) {
      int id = motionEvent.getPointerId(i);
      x_last[id] = x[id];
      y_last[id] = y[id];
      isTouch_last[id] = isTouch[id];
      x[id] = motionEvent.getX(i);
      y[id] = motionEvent.getY(i);
      }
     
     switch (action){
     case MotionEvent.ACTION_DOWN:
      isTouch[pointerId] = true;
      break;
     case MotionEvent.ACTION_POINTER_DOWN:
      isTouch[pointerId] = true;
      break;
     case MotionEvent.ACTION_MOVE:
      isTouch[pointerId] = true;
      break;
     case MotionEvent.ACTION_UP:
      isTouch[pointerId] = false;
      isTouch_last[pointerId] = false;
      break;
     case MotionEvent.ACTION_POINTER_UP:
      isTouch[pointerId] = false;
      isTouch_last[pointerId] = false;
      break;
     case MotionEvent.ACTION_CANCEL:
      isTouch[pointerId] = false;
      isTouch_last[pointerId] = false;
      break;
     default:
      isTouch[pointerId] = false;
      isTouch_last[pointerId] = false;
     }
    }
   }
   
   return true;
  }
     
    }
}


Related Post:
- Handle onTouchEvent in SurfaceView
- Draw path on SurfaceView's canvas

May 22, 2011

Change background color using Java code, setBackgroundColor()

Change background color using Java code, setBackgroundColor()

package com.AndroidBackgroundColor;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;

public class AndroidBackgroundColor extends Activity {

SeekBar seekRed, seekGreen, seekBlue, seekAlpha;
View targetView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

targetView = (View)findViewById(R.id.mainlayout);

seekRed = (SeekBar)findViewById(R.id.seekred);
seekGreen = (SeekBar)findViewById(R.id.seekgreen);
seekBlue = (SeekBar)findViewById(R.id.seekblue);
seekAlpha = (SeekBar)findViewById(R.id.seekalpha);

seekRed.setOnSeekBarChangeListener(seekChangeListener);
seekGreen.setOnSeekBarChangeListener(seekChangeListener);
seekBlue.setOnSeekBarChangeListener(seekChangeListener);
seekAlpha.setOnSeekBarChangeListener(seekChangeListener);
}

private SeekBar.OnSeekBarChangeListener seekChangeListener
= new SeekBar.OnSeekBarChangeListener(){

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

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

}

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

}};

private void updateBackgroundColor(){

int red = seekRed.getProgress();
int green = seekGreen.getProgress();
int blue = seekBlue.getProgress();
int alpha = seekAlpha.getProgress();

targetView.setBackgroundColor(
((alpha << 24) & 0xFF000000)
+ ((red << 16) & 0x00FF0000)
+ ((green << 8) & 0x0000FF00)
+ (blue & 0x000000FF));

}
}


<?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"
android:id="@+id/mainlayout"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="RED"
/>
<SeekBar
android:id="@+id/seekred"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="GREEN"
/>
<SeekBar
android:id="@+id/seekgreen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="BLUE"
/>
<SeekBar
android:id="@+id/seekblue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ALPHA"
/>
<SeekBar
android:id="@+id/seekalpha"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
/>
</LinearLayout>


May 21, 2011

Change Text color using setTextColor()

Change Text color using setTextColor()

package com.exercise.AndroidTextColor;

import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;

public class AndroidTextColor extends Activity {

SeekBar seekRed, seekGreen, seekBlue, seekAlpha;
TextView targetText;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

targetText = (TextView)findViewById(R.id.targetview);

seekRed = (SeekBar)findViewById(R.id.seekred);
seekGreen = (SeekBar)findViewById(R.id.seekgreen);
seekBlue = (SeekBar)findViewById(R.id.seekblue);
seekAlpha = (SeekBar)findViewById(R.id.seekalpha);

seekRed.setOnSeekBarChangeListener(seekChangeListener);
seekGreen.setOnSeekBarChangeListener(seekChangeListener);
seekBlue.setOnSeekBarChangeListener(seekChangeListener);
seekAlpha.setOnSeekBarChangeListener(seekChangeListener);
}

private SeekBar.OnSeekBarChangeListener seekChangeListener
= new SeekBar.OnSeekBarChangeListener(){

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

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

}

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

}};

private void updateTextColor(){

int red = seekRed.getProgress();
int green = seekGreen.getProgress();
int blue = seekBlue.getProgress();
int alpha = seekAlpha.getProgress();

targetText.setTextColor(
((alpha << 24) & 0xFF000000)
+ ((red << 16) & 0x00FF0000)
+ ((green << 8) & 0x0000FF00)
+ (blue & 0x000000FF));

}
}


<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="RED"
/>
<SeekBar
android:id="@+id/seekred"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="GREEN"
/>
<SeekBar
android:id="@+id/seekgreen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="BLUE"
/>
<SeekBar
android:id="@+id/seekblue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ALPHA"
/>
<SeekBar
android:id="@+id/seekalpha"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
/>
<TextView
android:id="@+id/targetview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="How to change Text Color?"
/>
</LinearLayout>


May 20, 2011

Hide and unhide a view

Hide and unhide a view

package com.AndroidHideView;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class AndroidHideView extends Activity {

TextView targetText;
Spinner spVisibility;

String[] optVisibility = { "VISIBLE",
"INVISIBLE",
"GONE"};

int[] valueVisibility = { View.VISIBLE,
View.INVISIBLE,
View.GONE};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

targetText = (TextView)findViewById(R.id.targetview);
spVisibility = (Spinner)findViewById(R.id.visibility);

ArrayAdapter<String> adapterVisibility = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, optVisibility);
adapterVisibility.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spVisibility.setAdapter(adapterVisibility);
spVisibility.setOnItemSelectedListener(spVisibilityOnItemSelectedListener);
}

private Spinner.OnItemSelectedListener spVisibilityOnItemSelectedListener
= new Spinner.OnItemSelectedListener(){

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub

int visibility = valueVisibility[spVisibility.getSelectedItemPosition()];
targetText.setVisibility(visibility);

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}};

}


<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Spinner
android:id="@+id/visibility"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="======================================="
/>
<TextView
android:id="@+id/targetview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This TextView can be hided and unhided."
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="======================================="
/>
</LinearLayout>


May 19, 2011

Change TextSize in run-time

Change TextSize in run-time

package com.AndroidTextSize;

import android.app.Activity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class AndroidTextSize extends Activity {

String[] optUnit = {"COMPLEX_UNIT_DIP",
"COMPLEX_UNIT_IN",
"COMPLEX_UNIT_MM",
"COMPLEX_UNIT_PT",
"COMPLEX_UNIT_PX",
"COMPLEX_UNIT_SP"};

int[] valueUnit = { TypedValue.COMPLEX_UNIT_DIP,
TypedValue.COMPLEX_UNIT_IN,
TypedValue.COMPLEX_UNIT_MM,
TypedValue.COMPLEX_UNIT_PT,
TypedValue.COMPLEX_UNIT_PX,
TypedValue.COMPLEX_UNIT_SP};

String[] optSize ={"0.05", "0.1", "0.25", "0.5", "1", "4", "8", "10", "14", "16", "20", "30"};
float[] valueSize = {0.05f, 0.1f, 0.25f, 0.5f, 1f, 4f, 8f, 10f, 14f, 16f, 20f, 30f};

Spinner selUnit, selSize;
TextView textOut;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

selUnit = (Spinner)findViewById(R.id.selunit);
selSize = (Spinner)findViewById(R.id.selsize);
textOut = (TextView)findViewById(R.id.textout);

ArrayAdapter<String> adapterUnit = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, optUnit);
adapterUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selUnit.setAdapter(adapterUnit);
selUnit.setOnItemSelectedListener(selUnitOnItemSelectedListener);

ArrayAdapter<String> adapterSize = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, optSize);
adapterSize.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selSize.setAdapter(adapterSize);
selSize.setOnItemSelectedListener(selSizeOnItemSelectedListener);
}

private Spinner.OnItemSelectedListener selUnitOnItemSelectedListener
= new Spinner.OnItemSelectedListener(){

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
updateTextSize();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}};

private Spinner.OnItemSelectedListener selSizeOnItemSelectedListener
= new Spinner.OnItemSelectedListener(){

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
updateTextSize();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}};

private void updateTextSize(){
int unit = valueUnit[selUnit.getSelectedItemPosition()];
String strUnit = optUnit[selUnit.getSelectedItemPosition()];
float size = valueSize[selSize.getSelectedItemPosition()];
String strSize = optSize[selSize.getSelectedItemPosition()];

textOut.setTextSize(unit, size);
textOut.setText(strUnit + " : " + strSize);
}
}


<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Spinner
android:id="@+id/selunit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Spinner
android:id="@+id/selsize"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/textout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>


Change typeface and style programmatically using Java Code

To change typeface and style of TextView, use the code:

textview.setTypeface(typeface, style);

where typeface can be:
  • Typeface.DEFAULT
  • Typeface.DEFAULT_BOLD
  • Typeface.MONOSPACE
  • Typeface.SANS_SERIF
  • Typeface.SERIF


style can be:
  • Typeface.BOLD
  • Typeface.BOLD_ITALIC
  • Typeface.ITALIC
  • Typeface.NORMAL


Change typeface and style programmatically using Java Code

package com.AndroidTypeface;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class AndroidTypeface extends Activity {

String[] optTypeface = {"DEFAULT",
"DEFAULT_BOLD",
"MONOSPACE",
"SANS_SERIF",
"SERIF"};

Typeface[] tfTypeface = { Typeface.DEFAULT,
Typeface.DEFAULT_BOLD,
Typeface.MONOSPACE,
Typeface.SANS_SERIF,
Typeface.SERIF};

String[] optStyle ={"BOLD",
"BOLD_ITALIC",
"ITALIC",
"NORMAL"};
int[] intStyle = { Typeface.BOLD,
Typeface.BOLD_ITALIC,
Typeface.ITALIC,
Typeface.NORMAL};

Spinner selTypeface, selStyle;
TextView textOut;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

selTypeface = (Spinner)findViewById(R.id.seltypeface);
selStyle = (Spinner)findViewById(R.id.selstyle);
textOut = (TextView)findViewById(R.id.textout);

ArrayAdapter<String> adapterTypeface = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, optTypeface);
adapterTypeface.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selTypeface.setAdapter(adapterTypeface);
selTypeface.setOnItemSelectedListener(selTypefaceOnItemSelectedListener);

ArrayAdapter<String> adapterStyle = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, optStyle);
adapterStyle.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selStyle.setAdapter(adapterStyle);
selStyle.setOnItemSelectedListener(selStyleOnItemSelectedListener);
}

private Spinner.OnItemSelectedListener selTypefaceOnItemSelectedListener
= new Spinner.OnItemSelectedListener(){

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
updateFront();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}};

private Spinner.OnItemSelectedListener selStyleOnItemSelectedListener
= new Spinner.OnItemSelectedListener(){

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
updateFront();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}};

private void updateFront(){
Typeface typeface = tfTypeface[selTypeface.getSelectedItemPosition()];
String familyName = optTypeface[selTypeface.getSelectedItemPosition()];
int style = intStyle[selStyle.getSelectedItemPosition()];
String stringStyle = optStyle[selStyle.getSelectedItemPosition()];

textOut.setTypeface(typeface, style);
textOut.setText(familyName + " : " + stringStyle);
}
}


<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Spinner
android:id="@+id/seltypeface"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Spinner
android:id="@+id/selstyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/textout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

May 18, 2011

Resize Button programmatically using Java Code

Buttons can be resized by changing and update LayoutParams.width and LayoutParams.height.

Resize Button programmatically using Java Code

Notice that the width and height return from Button.getWidth() and Button.getHeight() will not reflect the updated size at once. You can click the "Check my size" button to check the updated size.

package com.AndroidResizeView;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class AndroidResizeView extends Activity{

TextView textMyTextView, textViewWidth, textViewHeight;
Button myButton;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textMyTextView = (TextView)findViewById(R.id.mytextview);
textViewWidth = (TextView)findViewById(R.id.viewwidth);
textViewHeight = (TextView)findViewById(R.id.viewheight);
myButton = (Button)findViewById(R.id.mybutton);
Button btnIncWidth = (Button)findViewById(R.id.incwidth);
Button btnDecWidth = (Button)findViewById(R.id.decwidth);
Button btnIncHeight = (Button)findViewById(R.id.incheight);
Button btnDecHeight = (Button)findViewById(R.id.decheight);

btnIncWidth.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ViewGroup.LayoutParams params = myButton.getLayoutParams();
params.width++;
myButton.setLayoutParams(params);
updateSizeInfo();
}});

btnDecWidth.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ViewGroup.LayoutParams params = myButton.getLayoutParams();
params.width--;
myButton.setLayoutParams(params);
updateSizeInfo();
}});

btnIncHeight.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ViewGroup.LayoutParams params = myButton.getLayoutParams();
params.height++;
myButton.setLayoutParams(params);
updateSizeInfo();
}});

btnDecHeight.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ViewGroup.LayoutParams params = myButton.getLayoutParams();
params.height--;
myButton.setLayoutParams(params);
updateSizeInfo();
}});

myButton.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
updateSizeInfo();
}});
}


@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
updateSizeInfo();
}

private void updateSizeInfo(){

textViewWidth.setText(String.valueOf("Button's Width(pixels): " + myButton.getWidth()));
textViewHeight.setText(String.valueOf("Button's Height(pixels): " + myButton.getHeight()));
}

}


<?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"
>
<TextView
android:id="@+id/mytextview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/incwidth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button Width++"
/>
<Button
android:id="@+id/decwidth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button Width--"
/>
<Button
android:id="@+id/incheight"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button Height++"
/>
<Button
android:id="@+id/decheight"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button Height--"
/>
<Button
android:id="@+id/mybutton"
android:layout_width="200px"
android:layout_height="wrap_content"
android:text="Check my size"
/>
<TextView
android:id="@+id/viewwidth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/viewheight"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>




Get size (width, height) of a View

This example show how to read size of a view (Button in this example), using getWidth(), getHeight().

Get size (width, height) of a View

Be aware not to call getWidth() or getHeight() too early before the view have been laid out on the screen, otherwise "0" will be returned.

package com.AndroidResizeView;

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

public class AndroidResizeView extends Activity{

TextView textMyTextView, textViewWidth, textViewHeight;
Button myButton;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textMyTextView = (TextView)findViewById(R.id.mytextview);
textViewWidth = (TextView)findViewById(R.id.viewwidth);
textViewHeight = (TextView)findViewById(R.id.viewheight);
myButton = (Button)findViewById(R.id.mybutton);

myButton.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
updateSizeInfo();
}});
}


@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
updateSizeInfo();
}


private void updateSizeInfo(){

textViewWidth.setText(String.valueOf("Button's Width(pixels): " + myButton.getWidth()));
textViewHeight.setText(String.valueOf("Button's Height(pixels): " + myButton.getHeight()));
}

}


<?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"
>
<TextView
android:id="@+id/mytextview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/mybutton"
android:layout_width="200px"
android:layout_height="wrap_content"
android:text="Check my size"
/>
<TextView
android:id="@+id/viewwidth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/viewheight"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>


next:
- Resize Button programmatically using Java Code

May 16, 2011

Detect "natural" orientation of screen, using Display.getRotation()

Detect

package com.AndroidOrientation;

import android.app.Activity;
import android.content.Context;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Display;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidOrientation extends Activity{

TextView textOrientation;
MyOrientationEventListener myOrientationEventListener;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOrientation = (TextView)findViewById(R.id.textorientation);

myOrientationEventListener =
new MyOrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL);

if (myOrientationEventListener.canDetectOrientation()){
myOrientationEventListener.enable();
}else{
Toast.makeText(AndroidOrientation.this,
"Can't Detect Orientation!",
Toast.LENGTH_LONG).show();
}
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
myOrientationEventListener.disable();
}

class MyOrientationEventListener extends OrientationEventListener{

String prevOrientation = "";
String curOrientation = "";

public MyOrientationEventListener(Context context, int rate) {
super(context, rate);
// TODO Auto-generated constructor stub
}

@Override
public void onOrientationChanged(int arg0) {
// TODO Auto-generated method stub

Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
switch(display.getRotation()){
case(Surface.ROTATION_0):
curOrientation = "ROTATION_0";
break;
case(Surface.ROTATION_90):
curOrientation = "ROTATION_90";
break;
case(Surface.ROTATION_180):
curOrientation = "ROTATION_180";
break;
case(Surface.ROTATION_270):
curOrientation = "ROTATION_270";
break;
}

textOrientation.setText(curOrientation);

if (!curOrientation.equals(prevOrientation)){
Toast.makeText(AndroidOrientation.this, curOrientation, Toast.LENGTH_LONG).show();
prevOrientation = curOrientation;
}
}
}
}


May 12, 2011

Voice recognizer + Text to speech

Merge last two post; Start Android system's voice recognizer using Intent & Implement Android's Text to speech function.

Voice recognizer + Text to speech

Onec the recognized result selected, it will be speeched using TTS.

package com.AndroidRecognizer;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class AndroidRecognizer extends Activity implements OnInitListener{

TextToSpeech tts;

Button startRecognizer;
Spinner spinnerResult;

private static final int RQS_RECOGNITION = 1;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startRecognizer = (Button)findViewById(R.id.startrecognizer);
startRecognizer.setEnabled(false);

spinnerResult = (Spinner)findViewById(R.id.result);

startRecognizer.setOnClickListener(startRecognizerOnClickListener);

tts = new TextToSpeech(this, this);

}

private Button.OnClickListener startRecognizerOnClickListener
= new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech to Recognize");
startActivityForResult(intent, RQS_RECOGNITION);
}
};

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if((requestCode == RQS_RECOGNITION) & (resultCode == RESULT_OK)){

ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, result);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerResult.setAdapter(adapter);

spinnerResult.setOnItemSelectedListener(spinnerResultOnItemSelectedListener);

}

}

private Spinner.OnItemSelectedListener spinnerResultOnItemSelectedListener
= new Spinner.OnItemSelectedListener(){

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String selectedResult = parent.getItemAtPosition(position).toString();
Toast.makeText(AndroidRecognizer.this, selectedResult, Toast.LENGTH_SHORT).show();
tts.speak(selectedResult, TextToSpeech.QUEUE_ADD, null);

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}};

@Override
public void onInit(int arg0) {
// TODO Auto-generated method stub
startRecognizer.setEnabled(true);
}

}


<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/startrecognizer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start Recognizer"
/>
<Spinner
android:id="@+id/result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

May 11, 2011

Start Android system's voice recognizer using Intent

Result of Android system's voice recognizer

package com.AndroidRecognizer;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class AndroidRecognizer extends Activity {

Button startRecognizer;
Spinner spinnerResult;

private static final int RQS_RECOGNITION = 1;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startRecognizer = (Button)findViewById(R.id.startrecognizer);
spinnerResult = (Spinner)findViewById(R.id.result);

startRecognizer.setOnClickListener(startRecognizerOnClickListener);

}

private Button.OnClickListener startRecognizerOnClickListener
= new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech to Recognize");
startActivityForResult(intent, RQS_RECOGNITION);
}
};

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if((requestCode == RQS_RECOGNITION) & (resultCode == RESULT_OK)){

ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, result);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerResult.setAdapter(adapter);

}

}
}


<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/startrecognizer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start Recognizer"
/>
<Spinner
android:id="@+id/result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>


May 10, 2011

Implement Android's Text to speech function

Android's Text to speech function

package com.AndroidTTS;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AndroidTTS extends Activity implements OnInitListener{

TextToSpeech tts;
EditText textIn;
Button buttonSpeech;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

tts = new TextToSpeech(this, this);

textIn = (EditText)findViewById(R.id.textin);
buttonSpeech = (Button)findViewById(R.id.speech);

buttonSpeech.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String textToBeSpeech = textIn.getText().toString();
tts.speak(textToBeSpeech, TextToSpeech.QUEUE_ADD, null);
}});
}

@Override
public void onInit(int arg0) {
// TODO Auto-generated method stub
//Make sure the Text-To-Speech engine is fully loaded
//It can be configured and used
buttonSpeech.setEnabled(true);
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
tts.shutdown();
}
}


<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText
android:id="@+id/textin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/speech"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Speech"
android:enabled="false"
/>
</LinearLayout>


May 9, 2011

Make you App looked like a Dialog

To make your app looked like a dialog, you can use the Android pre-defined Theme.Dialog.

Modify AndroidManifest.xml, to add the code inside
android:theme="@android:style/Theme.Dialog"

example:
Make you App looked like a Dialog

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.AndroidDialog"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidDialog"
android:label="@string/app_name"
android:theme="@android:style/Theme.Dialog">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
</manifest>


May 8, 2011

Set background of your app to be transparent

To set background of your app to be transparent, you can use Android pre-defined Theme.Translucent.

Modify AndroidManifest.xml, to add the code inside <activity>
android:theme="@android:style/Theme.Translucent"

example:

Set background of your app to be transparent

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.AndroidTranslucent"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidTranslucent"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
</manifest>

May 6, 2011

Handle onTouchEvent in SurfaceView

Here Override onTouchEvent() in SurfaceView to handle user touch event.

Handle onTouchEvent in SurfaceView

package com.TestSurefaceView;

import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class TestSurefaceView extends Activity {
 
 MySurfaceView mySurfaceView;
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       mySurfaceView = new MySurfaceView(this);
       setContentView(mySurfaceView);
   }
  
   @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  mySurfaceView.onResumeMySurfaceView();
 }

 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  mySurfaceView.onPauseMySurfaceView();
 }

 class MySurfaceView extends SurfaceView implements Runnable{
    
    Thread thread = null;
    SurfaceHolder surfaceHolder;
    volatile boolean running = false;
    
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Random random;
    
    volatile boolean touched = false;
    volatile float touched_x, touched_y;

  public MySurfaceView(Context context) {
   super(context);
   // TODO Auto-generated constructor stub
   surfaceHolder = getHolder();
   random = new Random();
  }
  
  public void onResumeMySurfaceView(){
   running = true;
   thread = new Thread(this);
   thread.start();
  }
  
  public void onPauseMySurfaceView(){
   boolean retry = true;
   running = false;
   while(retry){
    try {
     thread.join();
     retry = false;
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }

  @Override
  public void run() {
   // TODO Auto-generated method stub
   while(running){
    if(surfaceHolder.getSurface().isValid()){
     Canvas canvas = surfaceHolder.lockCanvas();
     //... actual drawing on canvas

     paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3);
     
     int w = canvas.getWidth();
     int h = canvas.getHeight();
     int x = random.nextInt(w-1); 
     int y = random.nextInt(h-1);
     int r = random.nextInt(255);
     int g = random.nextInt(255);
     int b = random.nextInt(255);
     paint.setColor(0xff000000 + (r << 16) + (g << 8) + b);
     canvas.drawPoint(x, y, paint);
     
     if(touched){
      paint.setStrokeWidth(50);
      paint.setColor(Color.BLACK);
      canvas.drawPoint(touched_x, touched_y, paint);
     }
     
     surfaceHolder.unlockCanvasAndPost(canvas);
    }
   }
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
   // TODO Auto-generated method stub
   
   touched_x = event.getX();
   touched_y = event.getY();
   
   int action = event.getAction();
   switch(action){
   case MotionEvent.ACTION_DOWN:
    touched = true;
    break;
   case MotionEvent.ACTION_MOVE:
    touched = true;
    break;
   case MotionEvent.ACTION_UP:
    touched = false;
    break;
   case MotionEvent.ACTION_CANCEL:
    touched = false;
    break;
   case MotionEvent.ACTION_OUTSIDE:
    touched = false;
    break;
   default:
   }
   return true; //processed
  }
    
   }
}


Related Post:
- A basic implementation of SurfaceView
- Drawing on SurfaceView
- Detect multi-touch, on SurfaceView
- Draw path on SurfaceView's canvas

May 5, 2011

Drawing on SurfaceView

Last post introduce "A basic implementation of SurfaceView". To draw something on the SurfaceView, place the codes in-between surfaceHolder.lockCanvas() and surfaceHolder.unlockCanvasAndPost(canvas).

Drawing on SurfaceView

package com.TestSurefaceView;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class TestSurefaceView extends Activity {
 
 MySurfaceView mySurfaceView;
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       mySurfaceView = new MySurfaceView(this);
       setContentView(mySurfaceView);
   }
  
   @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  mySurfaceView.onResumeMySurfaceView();
 }

 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  mySurfaceView.onPauseMySurfaceView();
 }

 class MySurfaceView extends SurfaceView implements Runnable{
    
    Thread thread = null;
    SurfaceHolder surfaceHolder;
    volatile boolean running = false;
    
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Random random;

  public MySurfaceView(Context context) {
   super(context);
   // TODO Auto-generated constructor stub
   surfaceHolder = getHolder();
   random = new Random();
  }
  
  public void onResumeMySurfaceView(){
   running = true;
   thread = new Thread(this);
   thread.start();
  }
  
  public void onPauseMySurfaceView(){
   boolean retry = true;
   running = false;
   while(retry){
    try {
     thread.join();
     retry = false;
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }

  @Override
  public void run() {
   // TODO Auto-generated method stub
   while(running){
    if(surfaceHolder.getSurface().isValid()){
     Canvas canvas = surfaceHolder.lockCanvas();
     //... actual drawing on canvas

     paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3);
     
     int w = canvas.getWidth();
     int h = canvas.getHeight();
     int x = random.nextInt(w-1); 
     int y = random.nextInt(h-1);
     int r = random.nextInt(255);
     int g = random.nextInt(255);
     int b = random.nextInt(255);
     paint.setColor(0xff000000 + (r << 16) + (g << 8) + b);
     canvas.drawPoint(x, y, paint);
     
     surfaceHolder.unlockCanvasAndPost(canvas);
    }
   }
  }
    
   }
}


Related Post:
- Handle onTouchEvent in SurfaceView
- Draw path on SurfaceView's canvas

May 4, 2011

A basic implementation of SurfaceView

SurfaceView provides a dedicated drawing surface embedded inside of a view hierarchy. You can control the format of this surface and, if you like, its size; the SurfaceView takes care of placing the surface at the correct location on the screen.

Access to the underlying surface is provided via the SurfaceHolder interface, which can be retrieved by calling getHolder().

package com.TestSurefaceView;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class TestSurefaceView extends Activity {

MySurfaceView mySurfaceView;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       mySurfaceView = new MySurfaceView(this);
       setContentView(mySurfaceView);
   }
  
   @Override
protected void onResume() {
 // TODO Auto-generated method stub
 super.onResume();
 mySurfaceView.onResumeMySurfaceView();
}

@Override
protected void onPause() {
 // TODO Auto-generated method stub
 super.onPause();
 mySurfaceView.onPauseMySurfaceView();
}

class MySurfaceView extends SurfaceView implements Runnable{
   
    Thread thread = null;
    SurfaceHolder surfaceHolder;
    volatile boolean running = false;

 public MySurfaceView(Context context) {
  super(context);
  // TODO Auto-generated constructor stub
  surfaceHolder = getHolder();
 }

 public void onResumeMySurfaceView(){
  running = true;
  thread = new Thread(this);
  thread.start();
 }

 public void onPauseMySurfaceView(){
  boolean retry = true;
  running = false;
  while(retry){
   try {
    thread.join();
    retry = false;
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  while(running){
   if(surfaceHolder.getSurface().isValid()){
    Canvas canvas = surfaceHolder.lockCanvas();
    //... actual drawing on canvas
   
    surfaceHolder.unlockCanvasAndPost(canvas);
   }
  }
 }
   
   }
}


next:
- Drawing on SurfaceView
- Handle onTouchEvent in SurfaceView
- Draw path on SurfaceView's canvas

May 1, 2011

Detect Multi-Touch Event, test on Custom View

Detect Multi-Touch Event, test on Custom View

package com.TestMultiTouch;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class TestMultiTouch extends Activity {

public class MultiTouchView extends View{

//In this test, handle maximum of 2 pointer
final int MAX_POINT_CNT = 2;

private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
float[] x = new float[MAX_POINT_CNT];
float[] y = new float[MAX_POINT_CNT];
boolean[] isTouch = new boolean[MAX_POINT_CNT];

public MultiTouchView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
if(isTouch[0]){
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setColor(Color.RED);
canvas.drawCircle(x[0], y[0], 50f, paint);
}
if(isTouch[1]){
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setColor(Color.BLUE);
canvas.drawCircle(x[1], y[1], 50f, paint);
}
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}

@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
// TODO Auto-generated method stub

int pointerIndex = ((motionEvent.getAction() & MotionEvent.ACTION_POINTER_ID_MASK)
>> MotionEvent.ACTION_POINTER_ID_SHIFT);
int pointerId = motionEvent.getPointerId(pointerIndex);
int action = (motionEvent.getAction() & MotionEvent.ACTION_MASK);
int pointCnt = motionEvent.getPointerCount();

if (pointCnt <= MAX_POINT_CNT){
if (pointerIndex <= MAX_POINT_CNT - 1){

for (int i = 0; i < pointCnt; i++) {
int id = motionEvent.getPointerId(i);
x[id] = (int)motionEvent.getX(i);
y[id] = (int)motionEvent.getY(i);
}

switch (action){
case MotionEvent.ACTION_DOWN:
isTouch[pointerId] = true;
break;
case MotionEvent.ACTION_POINTER_DOWN:
isTouch[pointerId] = true;
break;
case MotionEvent.ACTION_MOVE:
isTouch[pointerId] = true;
break;
case MotionEvent.ACTION_UP:
isTouch[pointerId] = false;
break;
case MotionEvent.ACTION_POINTER_UP:
isTouch[pointerId] = false;
break;
case MotionEvent.ACTION_CANCEL:
isTouch[pointerId] = false;
break;
default:
isTouch[pointerId] = false;
}
}
}

invalidate();
return true;
}

}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MultiTouchView(this));
}
}



Related Post:
- Detect Touch Event
- Detect Touch Event, test on Custom View
- Detect Multi-Touch Event

Infolinks In Text Ads