Friday, June 29, 2012

Android: Understating Text Drawing

When it comes to draw text inside our custom view, it is difficult to position text vertically in correct place if we use canvas.drawText(..,x,y..) , because it will not start to draw from the give y coordinate rather it will position the text base line in the give y coordinate.

First look at this following image:

In the first view (view 01) text and a red line are drawn in the middle vertically.
         TEXT_PAINT.setColor(Color.WHITE);
        //Drawing the text at middle of the view
canvas.drawText(LONG_STRING, 0, getHeight()/2, TEXT_PAINT);
TEXT_PAINT.setColor(Color.RED);
//Here we draw the middle line
canvas.drawLine(0, getHeight()/2, getWidth(), getHeight()/2, TEXT_PAINT);

If you think that, the text is drawn on top of the line, then simply if we find an API to get the height of the text then we can align use that value.
Rect rect = new Rect();
TEXT_PAINT.setColor(Color.BLUE);
TEXT_PAINT.getTextBounds(LONG_STRING, 0, LONG_STRING.length(), rect);
//Measure the height and draw line on top of text
canvas.drawLine(0, getHeight()/2-rect.height(), getWidth(), getHeight()/2-rect.height(), TEXT_PAINT);

But that is not the case, you see, some part of 'y' from 'Please try this is...' is drawn down of the middle line. So we want to know how actually text are drawn and actual center of the text.


To understand this I used StaticLayout in the second view (view 02).
TEXT_PAINT.setColor(Color.WHITE);
 //Create a static layout to draw 
StaticLayout staticLayout = new StaticLayout(
LONG_STRING, 0, LONG_STRING.length(),
TEXT_PAINT,
                                                 getWidth(),android.text.Layout.Alignment.ALIGN_CENTER , 
1.0f, 1.0f, false);
staticLayout.draw(canvas);


It provides necessary API to get top, bottom and base line of the text. In the second view you can see those lines.
for(int i = 0 ; i < staticLayout.getLineCount();i++){
TEXT_PAINT.setColor(Color.BLUE);
canvas.drawLine(0, staticLayout.getLineTop(i), getWidth(), staticLayout.getLineTop(i), TEXT_PAINT);
TEXT_PAINT.setColor(0x7FFFFFFF&Color.YELLOW);
canvas.drawRect(staticLayout.getLineLeft(i), staticLayout.getLineTop(i), staticLayout.getLineRight(i), staticLayout.getLineBottom(i), TEXT_PAINT);
TEXT_PAINT.setColor(Color.RED);
canvas.drawLine(0, staticLayout.getLineBaseline(i), getWidth(), staticLayout.getLineBaseline(i), TEXT_PAINT);
TEXT_PAINT.setColor(Color.MAGENTA);
canvas.drawLine(0, staticLayout.getLineBottom(i), getWidth(), staticLayout.getLineBottom(i), TEXT_PAINT);
}

Now let use this values to draw text in proper place as shown in view 03.
canvas.drawText(LONG_STRING, 0, getHeight()/2+(staticLayout.getLineBaseline(0)-staticLayout.getLineBottom(0)/2), TEXT_PAINT);


I have uploaded sample source code here:
Thanks


Wednesday, June 27, 2012

Android: Play video on Top of GLSurfaceView



i modified the GLSurfaceViewActivity from ApiDemo to check to see where can play Video on top of GLSurfaceView.



public class GLSurfaceViewActivity extends Activity implements OnClickListener, OnCompletionListener, OnTouchListener {

@SuppressWarnings("unused")
private static final String TAG = "com.example.android.apis.graphics.GLSurfaceViewActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create our Preview view and set it as the content of our
        // Activity
        mGLSurfaceView = new GLSurfaceView(this);
        mGLSurfaceView.setOnTouchListener(this);
        mGLSurfaceView.setRenderer(new CubeRenderer(false));
        FrameLayout frameLayout = new FrameLayout(this);
        frameLayout.addView(mGLSurfaceView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,FrameLayout.LayoutParams.FILL_PARENT));
       
        mVideoView = new VideoView(this);
        mVideoView.setVisibility(View.INVISIBLE);
        mVideoView.setOnCompletionListener(this);
frameLayout.addView(mVideoView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,FrameLayout.LayoutParams.FILL_PARENT));
       
        mCheckBox = new CheckBox(this);
        mCheckBox.setText("Load Video");
        mCheckBox.setOnClickListener(this);
frameLayout.addView(mCheckBox, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT,Gravity.CENTER));
        setContentView(frameLayout);
    }

    @Override
    protected void onResume() {
        // Ideally a game should implement onResume() and onPause()
        // to take appropriate action when the activity looses focus
        super.onResume();
        mGLSurfaceView.onResume();
    }

    @Override
    protected void onPause() {
        // Ideally a game should implement onResume() and onPause()
        // to take appropriate action when the activity looses focus
        super.onPause();
        mGLSurfaceView.onPause();
    }

    private GLSurfaceView mGLSurfaceView;
private VideoView mVideoView;
private CheckBox mCheckBox;

@Override
public void onClick(View arg0) {
if(mCheckBox.isChecked()){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
startActivityForResult(Intent.createChooser(intent, "Chose a Video"), 10);
}else{
mVideoView.setVisibility(View.VISIBLE);
mVideoView.start();
mCheckBox.setChecked(true);
}

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(data!=null && data.getData()!=null){
mCheckBox.setText("Play Video");
mVideoView.setVideoURI(data.getData());
mVideoView.setVisibility(View.VISIBLE);
mVideoView.start();
}else{
mCheckBox.setChecked(false);
}
super.onActivityResult(requestCode, resultCode, data);
}

@Override
public void onCompletion(MediaPlayer arg0) {
mVideoView.setVisibility(View.INVISIBLE);

}

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mVideoView.setTranslationX(motionEvent.getX());
mVideoView.setTranslationY(motionEvent.getY());
return true;
}
}



Tuesday, June 26, 2012

Logging Caller Method Info in Java

In our application, one method maybe called from multiple locations. While debugging application we may need to log it caller caller method information in those case following line will be use full.
Here from the current thread, I get called Stack and print that for us.


private static void someMethod() {
System.out.println(Thread.currentThread().getStackTrace()[0]);
System.out.println(Thread.currentThread().getStackTrace()[1]);
System.out.println(Thread.currentThread().getStackTrace()[2]);
}


java.lang.Thread.getStackTrace(Thread.java:1479)
demo.TestThread.someMethod(TestThread.java:14)
demo.TestThread.main(TestThread.java:9)

What we want from this output is "demo.TestThread.main(TestThread.java:9)" So you use in your java application.

System.out.println(Thread.currentThread().getStackTrace()[2]);  


Okey for Android Application I try followings:

public void onCreate(Bundle savedInstanceState) {
..................

        Log.i(TAG, "::onCreate:" +Thread.currentThread().getStackTrace()[0]);
        Log.i(TAG, "::onCreate:" +Thread.currentThread().getStackTrace()[1]);
        Log.i(TAG, "::onCreate:" +Thread.currentThread().getStackTrace()[2]);
        Log.i(TAG, "::onCreate:" +Thread.currentThread().getStackTrace()[3]);

............
}


onCreate:dalvik.system.VMStack.getThreadStackTrace(Native Method)
onCreate:java.lang.Thread.getStackTrace(Thread.java:591)
onCreate:demo.multi.line.text.DemoMultiLineTextActivity.onCreate(DemoMultiLineTextActivity.java:58)
onCreate:android.app.Activity.performCreate(Activity.java:4518)


What we want from this output is "onCreate:android.app.Activity.performCreate(Activity.java:4518)" So you use in your Android application:

        Log.i(TAG, "::onCreate:" +Thread.currentThread().getStackTrace()[3]);




Friday, June 22, 2012

Android: Bigger Image for any of the Image inside Grid View

As and extension for my earlier post, I have created the project to apply for any of the image in the grid and it will support for any number of columns and the bigger image and can take any number of column with.


I have uploaded the source code here:  http://dl.dropbox.com/u/7717254/DemoGridView_02.zip

But if you have bigger image column size if greater than half of the grid column size it has some bug, and need to fix that first.

Wednesday, June 20, 2012

Android: Bigger image for first item of the gridview

Say you want layout like below:

I start to implement with following XML , activity, adapter:



<?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" >

        <GridView
            android:id="@+id/gridView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:numColumns="5" >
        </GridView>

</LinearLayout>



package demo.grid.view;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class DemoGridViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        GridView gridView = (GridView)findViewById(R.id.gridView1);
        gridView.setAdapter(new GridViewAdaptor());
    }
 
    class GridViewAdaptor extends BaseAdapter{

@Override
public int getCount() {
return 50;
}

@Override
public Object getItem(int arg0) {
return arg0;
}

@Override
public long getItemId(int arg0) {
return arg0;
}

@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView imageView;
if(arg1==null){
imageView = new ImageView(DemoGridViewActivity.this){
@Override
protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
}
};
}else{
imageView = (ImageView) arg1;
}

imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
imageView.setBackgroundColor(Color.BLUE);
imageView.setScaleType(ScaleType.FIT_XY);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
switch(arg0){
case 0:
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.RED);
return imageView;
case 1:
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, bitmap.getWidth()/2, 0, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.GREEN);
return imageView;
case 5:
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, 0, bitmap.getHeight()/2, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.YELLOW);
return imageView;
case 6:
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.MAGENTA);
return imageView;
default:
imageView.setImageResource(R.drawable.ic_launcher);
return imageView;
}
}
   
    }
}



Now this issue is how to work with a list of object and translate it into this grid view. Following translation needed to be done for adapter:

@Override
public int getCount() {
return integers.size()+3;
}


switch(arg0){
case 0:
imageView.setTag(integers.get(0));

case 1:
imageView.setTag(integers.get(0));
case 5:
imageView.setTag(integers.get(0));

case 6:
imageView.setTag(integers.get(0));
default:
if(arg0>1 && arg0<=4){
imageView.setTag(integers.get(arg0-1));
}else{
imageView.setTag(integers.get(arg0-3));
}
}

full code is here:

package demo.grid.view;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class DemoGridViewActivity extends Activity {
    /** Called when the activity is first created. */


List integers = new ArrayList();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        for(int i = 0 ; i < 50 ; i++){
        integers.add(i);
        }
     
        GridView gridView = (GridView)findViewById(R.id.gridView1);
        gridView.setAdapter(new GridViewAdaptor());
    }
 
    class GridViewAdaptor extends BaseAdapter{

@Override
public int getCount() {
return integers.size()+3;
}

@Override
public Object getItem(int arg0) {
return arg0;
}

@Override
public long getItemId(int arg0) {
return arg0;
}

@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView imageView;
if(arg1==null){
imageView = new ImageView(DemoGridViewActivity.this){
@Override
protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(36);
canvas.drawText(getTag().toString(), getWidth()/2, getHeight()/2, paint);
}
};
}else{
imageView = (ImageView) arg1;
}

imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
imageView.setBackgroundColor(Color.BLUE);
imageView.setScaleType(ScaleType.FIT_XY);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
switch(arg0){
case 0:
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.RED);
imageView.setTag(integers.get(0));
return imageView;
case 1:
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, bitmap.getWidth()/2, 0, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.GREEN);
imageView.setTag(integers.get(0));
return imageView;
case 5:
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, 0, bitmap.getHeight()/2, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.YELLOW);
imageView.setTag(integers.get(0));
return imageView;
case 6:
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.MAGENTA);
imageView.setTag(integers.get(0));
return imageView;
default:
if(arg0>1 && arg0<=4){
imageView.setTag(integers.get(arg0-1));
}else{
imageView.setTag(integers.get(arg0-3));
}

imageView.setImageResource(R.drawable.ic_launcher);
return imageView;
}
}
   
    }
}



finally this code for loading images from device sdcard and display in the gridview:





package demo.grid.view;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Thumbnails;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
public class DemoGridViewActivity extends Activity {
    private static final int START_PROGRESS = 10;
List mBitmaps = new ArrayList();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        AsyncTask asyncTask = new AsyncTask(){
        @Override
        protected void onPreExecute() {
        showDialog(START_PROGRESS);
        super.onPreExecute();
        }
@Override
protected Void doInBackground(Void... params) {
Cursor query = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, null, null, null);
if(query!=null && query.moveToFirst()){
do{
int columnIndex = query.getColumnIndex(MediaStore.Images.Media._ID);
long origId = query.getLong(columnIndex);
mBitmaps.add(MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), origId, Thumbnails.MICRO_KIND, null));
}while(query.moveToNext());
query.close();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
removeDialog(START_PROGRESS);
       GridView gridView = (GridView)findViewById(R.id.gridView1);
       gridView.setAdapter(new GridViewAdaptor());
super.onPostExecute(result);
}
        };
        asyncTask.execute();
    }
    @Override
    protected Dialog onCreateDialog(int id, Bundle args) {
    return new ProgressDialog(this);
    }
    class GridViewAdaptor extends BaseAdapter{
@Override
public int getCount() {
return mBitmaps.size()+3;
}
@Override
public Object getItem(int arg0) {
return arg0;
}
@Override
public long getItemId(int arg0) {
return arg0;
}
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView imageView;
if(arg1==null){
imageView = new ImageView(DemoGridViewActivity.this){
@Override
protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
}
};
}else{
imageView = (ImageView) arg1;
}
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
imageView.setBackgroundColor(Color.BLUE);
imageView.setScaleType(ScaleType.FIT_XY);

Bitmap bitmap;
switch(arg0){
case 0:
imageView.setPadding(10, 10, 0, 0);
bitmap = mBitmaps.get(0);
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.RED);
return imageView;
case 1:
imageView.setPadding(0, 10, 10, 0);
bitmap = mBitmaps.get(0);
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, bitmap.getWidth()/2, 0, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.GREEN);
return imageView;
case 5:
imageView.setPadding(10, 0, 0, 10);
bitmap = mBitmaps.get(0);
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, 0, bitmap.getHeight()/2, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.YELLOW);
return imageView;
case 6:
imageView.setPadding(0, 0, 10, 10);
bitmap = mBitmaps.get(0);
imageView.setImageBitmap(Bitmap.createBitmap(bitmap, bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, bitmap.getHeight()/2));
imageView.setBackgroundColor(Color.MAGENTA);
return imageView;
default:
if(arg0>1 && arg0<=4){
bitmap = mBitmaps.get(arg0-1);
}else{
bitmap = mBitmaps.get(arg0-3);
}
imageView.setPadding(10, 10, 10, 10);
imageView.setImageBitmap(bitmap);
return imageView;
}
}
    }
}



here you have sample code: source code

please check this post for more update: http://sudarnimalan.blogspot.sg/2012/06/android-bigger-image-for-any-of-image.html

Tuesday, June 19, 2012

Part1 : Useful Eclipse Templates for Android Development

I normally setup eclipse templates for repeat coding fragments. If you are not aware of eclipse editor templates, just a small example: just open a java code file and type "syso" (shortcut name) and press Ctrl+space then you will see all  "System.out.println();" will be inserted by eclipse for you.
To see all existing templates and its shortcut open your eclipse, open the window menu and click on Preference. Inside the Preference dialog , navigate to Java --> Editor --> Templates, Now you see full list there. (Eclipse-->Window-->Preference-->Java-->Editor-->Templates)
You can add your own templates there and make use of them in your coding and make your coding fast. Just click "New.." button, fill the "New Template" Dialog and OK.

1. In android, in case if we want to get logs we want to insert "Log.i" statements with proper message. This template will be useful for that.

Name: alog
Context: Java statements
Description: android log statement
Pattern: Log.i(TAG,"::${enclosing_method}:"+"${cursor}");

Now,For Example, in side onCreate  if you type alog and press Ctrl+space you will get:
Log.i(TAG, "::onCreate:" + ""); 

2. In #1 you see, we have to pass a TAG, normally this should be the Class name of the method we define in the top. I used to go for a full qualified name of any class. Sometime this will be useful in case of Custom Views to copy its name to crate layout XML files.


Name: atag
Context: Java type members
Description: android log tag
Pattern: 

@SuppressWarnings("unused")
private static final String TAG = "${enclosing_package}.${enclosing_type}";


Ex: @SuppressWarnings("unused")
private static final String TAG = "demo.DemoAcitity";


3. Inside the activity most we have to find View By Id and call some method on it.


Name: afind
Context: Java
Description: android find view
Pattern: 

${type} ${new_name} = (${type})findViewById(R.id.${cursor});

type afind and press Ctrl+Space, then you will get:
type| new_name = (type)findViewById(R.id.);

for example if that is a button then, type Button or But and press Ctrl+Space then you will get:
Button new_name = (Button)findViewById(R.id.);

Then press Tab cursor will move to new_name
Button new_name = (Button)findViewById(R.id.);

Type the name you want for the variable, then press Tab cursor will move after ".id.":
Button button = (Button)findViewById(R.id.|);
The just press Ctrl+space and choose the id from the list.

So you will end as follows:
Button button = (Button)findViewById(R.id.btn_add);

In android we mostly do this in onCreate method and assign to member variable. and refer from other method. Now you right click on the variable name choose Refactor  and choose "Convert Local Variable to Field" this will create a Field for you.


here i have uploaded the template file.

Part 2 : Useful Eclipse Templates for Android Development

Monday, June 18, 2012

Android: LinearLayout, Dynamically Arranging Views

Let see how to arrange buttons according to the user selection as shown below:


<LinearLayout android:orientation="vertical" android:id="@+id/linearLayout1"
     android:layout_height="fill_parent" android:layout_width="fill_parent">
    <Button android:text="Button" android:id="@+id/button0"
          android:layout_height="fill_parent" android:layout_width="fill_parent"
          android:layout_weight="1">Button>
     <Button android:text="Button" android:id="@+id/button1"
          android:layout_height="fill_parent" android:layout_width="fill_parent"
          android:layout_weight="1" android:visibility="gone">Button>
     <Button android:text="Button" android:id="@+id/button2"
          android:layout_height="fill_parent" android:layout_weight="1"
          android:layout_width="fill_parent" android:visibility="gone">Button>
LinearLayout>


Following java code would change the visibility according to the user selection.

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
     switch(group.getCheckedRadioButtonId()){
     case R.id.radio0:
          button0.setVisibility(View.VISIBLE);
          button1.setVisibility(View.GONE);
          button2.setVisibility(View.GONE);
          break;
     case R.id.radio1:
          button0.setVisibility(View.VISIBLE);
          button1.setVisibility(View.VISIBLE);
          button2.setVisibility(View.GONE);
          break;
     case R.id.radio2:
          button0.setVisibility(View.VISIBLE);
          button1.setVisibility(View.VISIBLE);
          button2.setVisibility(View.VISIBLE);
          break
      }
}

Let see if we want a layout to change as show below:
This can be down in two ways.
Option 01: changing the layout XML file to use the weight sum:

<LinearLayout android:orientation="vertical" android:id="@+id/linearLayout1"
     android:layout_height="fill_parent" android:layout_width="fill_parent" android:weightSum="3">
     <Button android:text="Button" android:id="@+id/button0"
          android:layout_width="fill_parent"
          android:layout_weight="1" android:layout_height="0dip">Button>
     <Button android:text="Button" android:id="@+id/button1"
          android:layout_width="fill_parent"
          android:layout_weight="1" android:visibility="gone" android:layout_height="0dip">        Button>
     <Button android:text="Button" android:id="@+id/button2"
          android:layout_weight="1"
          android:layout_width="fill_parent" android:visibility="gone" android:layout_height="0dip">Button>
LinearLayout>

Option 02: using java code:

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
     switch(group.getCheckedRadioButtonId()){
     case R.id.radio0:
          button0.setVisibility(View.VISIBLE);
          button1.setVisibility(View.INVISIBLE);
          button2.setVisibility(View. INVISIBLE);
          break;
     case R.id.radio1:
          button0.setVisibility(View.VISIBLE);
          button1.setVisibility(View.VISIBLE);
          button2.setVisibility(View. INVISIBLE);
          break;
     case R.id.radio2:
          button0.setVisibility(View.VISIBLE);
          button1.setVisibility(View.VISIBLE);
          button2.setVisibility(View.VISIBLE);
          break
      }
}

option 01 you should change the xml file and in option 02 you should change the java code.