Android Tutorial - Ui Layout

Load Layout from xml layout file

    

package app.Test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class appTest extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }

  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);
    return true;
  }

  public boolean onOptionsItemSelected(MenuItem item) {
    LinearLayout bkgr = (LinearLayout) findViewById(R.id.uilayout);
    final ImageView image = (ImageView) findViewById(R.id.ImageView01);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Pick an Image!")
        .setMessage("Please Select Image One or Image Two:")
        .setCancelable(false)
        .setPositiveButton("IMAGE 1",
            new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                image.setImageResource(R.drawable.image1);
              }
            })

        .setNegativeButton("IMAGE 2",
            new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                image.setImageResource(R.drawable.image2);
              }
            });

    switch (item.getItemId()) {
    case R.id.buttonone:
      image.setImageResource(R.drawable.image1);
      return true;
    case R.id.buttontwo:
      image.setImageResource(R.drawable.image2);
      return true;
    case R.id.buttonthree:
      bkgr.setBackgroundResource(R.color.background2);
      return true;
    case R.id.buttonfour:
      bkgr.setBackgroundResource(R.color.background);
      return true;
    case R.id.buttonfive:
      builder.show();
      return true;
    default:
      return super.onOptionsItemSelected(item);
    }
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/uilayout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/background">
    
  <ImageButton android:id="@+id/button_one"
          android:layout_width="wrap_content"
         android:layout_height="wrap_content"
          android:src="@drawable/button1"
          android:paddingTop="5px"
          android:background="#00000000">
  </ImageButton>
  
  <TextView  android:id="@+id/TextView01" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Sample Text" 
        android:textColor="#CCCC77" 
        android:padding="12dip">
  </TextView>
  
  <ImageView  android:id="@+id/ImageView01" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:src="@drawable/image1">
  </ImageView>
  
</LinearLayout>


//mainmenu.xml
<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/buttonone"
          android:icon="@drawable/image1icon"
          android:title="@string/showimage1" />
          
    <item android:id="@+id/buttontwo"
          android:icon="@drawable/image2icon"
          android:title="@string/showimage2" />
          
    <item android:id="@+id/buttonthree"
          android:icon="@drawable/menu3icon"
          android:title="@string/showwhite" />
          
    <item android:id="@+id/buttonfour"
          android:icon="@drawable/menu4icon"
          android:title="@string/showblack" />
          
    <item android:id="@+id/buttonfive"
          android:icon="@drawable/menu5icon"
          android:title="@string/showalert" />
          
</menu>

Using LayoutParams

      

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;


public class Test extends Activity
{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout view = new LinearLayout(this);

        view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        view.setOrientation(LinearLayout.HORIZONTAL);

        TextView nameLbl = new TextView(this);

        nameLbl.setText("Hello from PrivActivity");
        view.addView(nameLbl);

        setContentView(view);

    }
}
Align along with Parent
package com.example.android.apis.view;

import com.example.android.apis.R;

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


/**
 * Baseline alignment in RelativeLayout with various font weights.
 */
public class Baseline7 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:id="@+id/anchor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:textStyle="bold"
        android:text="baseline_7_fat" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignBaseline="@id/anchor"
        android:layout_height="wrap_content"
        android:text="baseline_7_lean" />
    
</RelativeLayout>

Set baselineAlignedChildIndex

package com.example.android.apis.view;

import com.example.android.apis.R;

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

/**
 * Baseline alignment includes an element within a nested horizontal
 * {@link android.widget.LinearLayout}.
 */
public class BaselineNested2 extends Activity {

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

        setContentView(R.layout.main);
    }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="3dip"
        android:layout_gravity="center_vertical"
        android:text="baseline_nested_1_label" />

    <!-- We want the middle textview of this vertical linear layout to
      be baseline aligned with the others.-->
    <LinearLayout
            android:orientation="vertical"
            android:baselineAlignedChildIndex="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/arrow_up_float"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dip"
            android:text="baseline_nested_1_label" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/arrow_down_float"/>
    </LinearLayout>


    <!-- We want the third index textview of this vertical linear layout to
      be baseline aligned with the others.-->
    <LinearLayout
            android:orientation="horizontal"
            android:baselineAlignedChildIndex="2"
            android:layout_width="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_height="wrap_content">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/arrow_up_float"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/arrow_up_float"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dip"
            android:text="baseline_nested_1_label" />
    </LinearLayout>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_gravity="center_vertical"
        android:text="baseline_nested_1_label" />


</LinearLayout>

Baseline nested

package com.example.android.apis.view;

import com.example.android.apis.R;

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

/**
 * Baseline alignment includes elements within nested vertical
 * {@link android.widget.LinearLayout}s.
 */
public class BaselineNested1 extends Activity {

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

        setContentView(R.layout.main);
    }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="3dip"
        android:layout_gravity="center_vertical"
        android:text="baseline_nested_1_label" />

    <!-- We want the middle textview of this vertical linear layout to
      be baseline aligned with the others.-->
    <LinearLayout
            android:orientation="vertical"
            android:baselineAlignedChildIndex="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/arrow_up_float"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dip"
            android:text="baseline_nested_1_label" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/arrow_down_float"/>
    </LinearLayout>


    <!-- We want the third index textview of this vertical linear layout to
      be baseline aligned with the others.-->
    <LinearLayout
            android:orientation="vertical"
            android:baselineAlignedChildIndex="2"
            android:layout_width="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_height="wrap_content">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/arrow_up_float"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/arrow_up_float"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dip"
            android:text="baseline_nested_1_label" />
    </LinearLayout>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_gravity="center_vertical"
        android:text="baseline_nested_1_label" />


</LinearLayout>

Set right margin

package com.example.android.apis.view;


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


/**
 * Baseline alignment in LinearLayout.
 */
public class Baseline1 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baseline_1);
    }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="3dip"
        android:text="baseline_1_label" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="3dip"
        android:text="baseline_1_button" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="baseline_1_bigger" />

</LinearLayout>

Set text Size

package com.example.android.apis.view;


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


/**
 * Baseline alignment in LinearLayout.
 */
public class Baseline1 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baseline_1);
    }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="3dip"
        android:text="baseline_1_label" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="3dip"
        android:text="baseline_1_button" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="baseline_1_bigger" />

</LinearLayout>

Layout Utils

//package com.onerm.ui;

import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;

public class LayoutUtils {

  public enum Layout {
    WidthFill_HeightFill,
    WidthWrap_HeightWrap,
    WidthWrap_HeightFill,
    WidthFill_HeightWrap;

    public void applyViewGroupParams(View component) {
      applyViewGroupLayoutParamsTo(this, component);
    }

    public void applyLinearLayoutParams(View linearlayout) {
      applyLinearLayoutParamsTo(this, linearlayout);
    }

    public void applyTableRowParams(View cell) {
      applyTableRowLayoutParamsTo(this, cell);
    }

    public void applyTableLayoutParams(View row) {
      applyTableLayoutParamsTo(this, row);
    }

  }

  private static void applyLinearLayoutParamsTo(Layout layout, View view) {

    switch (layout) {
      case WidthFill_HeightFill:
        view.setLayoutParams(new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.FILL_PARENT));
        break;
      case WidthFill_HeightWrap:
        view.setLayoutParams(new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));
        break;
      case WidthWrap_HeightFill:
        view.setLayoutParams(new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.FILL_PARENT));
        break;
      case WidthWrap_HeightWrap:
        view.setLayoutParams(new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));
        break;
    }

  }

  private static void applyViewGroupLayoutParamsTo(Layout layout, View view) {

    switch (layout) {
      case WidthFill_HeightFill:
        view.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.FILL_PARENT));
        break;
      case WidthFill_HeightWrap:
        view.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
        break;
      case WidthWrap_HeightFill:
        view.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.FILL_PARENT));
        break;
      case WidthWrap_HeightWrap:
        view.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
        break;
    }

  }

  private static void applyTableRowLayoutParamsTo(Layout layout, View view) {
    switch (layout) {
      case WidthFill_HeightFill:
        view.setLayoutParams(new TableRow.LayoutParams(
            TableRow.LayoutParams.FILL_PARENT,
            TableRow.LayoutParams.FILL_PARENT));
        break;
      case WidthFill_HeightWrap:
        view.setLayoutParams(new TableRow.LayoutParams(
            TableRow.LayoutParams.FILL_PARENT,
            TableRow.LayoutParams.WRAP_CONTENT));
        break;
      case WidthWrap_HeightFill:
        view.setLayoutParams(new TableRow.LayoutParams(
            TableRow.LayoutParams.WRAP_CONTENT,
            TableRow.LayoutParams.FILL_PARENT));
        break;
      case WidthWrap_HeightWrap:
        view.setLayoutParams(new TableRow.LayoutParams(
            TableRow.LayoutParams.WRAP_CONTENT,
            TableRow.LayoutParams.WRAP_CONTENT));
        break;
    }

  }

  private static void applyTableLayoutParamsTo(Layout layout, View view) {
    switch (layout) {
      case WidthFill_HeightFill:
        view.setLayoutParams(new TableLayout.LayoutParams(
            TableLayout.LayoutParams.FILL_PARENT,
            TableLayout.LayoutParams.FILL_PARENT));
        break;
      case WidthFill_HeightWrap:
        view.setLayoutParams(new TableLayout.LayoutParams(
            TableLayout.LayoutParams.FILL_PARENT,
            TableLayout.LayoutParams.WRAP_CONTENT));
        break;
      case WidthWrap_HeightFill:
        view.setLayoutParams(new TableLayout.LayoutParams(
            TableLayout.LayoutParams.WRAP_CONTENT,
            TableLayout.LayoutParams.FILL_PARENT));
        break;
      case WidthWrap_HeightWrap:
        view.setLayoutParams(new TableLayout.LayoutParams(
            TableLayout.LayoutParams.WRAP_CONTENT,
            TableLayout.LayoutParams.WRAP_CONTENT));
        break;
    }
  }

  public static void addLeftOfRule(RelativeLayout.LayoutParams params, View view) {
    params.addRule(RelativeLayout.LEFT_OF, view.getId());
  }

  public static void addRightOfRule(RelativeLayout.LayoutParams params, View view) {
    params.addRule(RelativeLayout.RIGHT_OF, view.getId());
  }
}

   

Inflate Layout

    
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

class Main {
  static public View inflate(Context context, int layoutId) {
    LayoutInflater vi = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    return vi.inflate(layoutId, null);
  }

  static public View inflate(Context context, int layoutId, View parent) {
    View v = inflate(context, layoutId);
    ((ViewGroup) parent).addView(v);
    return v;
  }

  static public View inflate(Activity context, int layoutId, int parentId) {
    View v = inflate(context, layoutId);
    ((ViewGroup) context.findViewById(parentId)).addView(v);
    return v;
  }

}

Create LayoutParam

    
//package com.akjava.lib.android.ui;

import java.io.BufferedInputStream;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;



 class WidgetUtil {
    public static LinearLayout.LayoutParams createLayoutParam(boolean fillWidth,boolean fillHeight){
      int w= LinearLayout.LayoutParams.WRAP_CONTENT;
      int h= LinearLayout.LayoutParams.WRAP_CONTENT;
      if(fillWidth){
        w= LinearLayout.LayoutParams.FILL_PARENT;
      }
      if(fillHeight){
        h=LinearLayout.LayoutParams.FILL_PARENT;
      }
      return new LinearLayout.LayoutParams(w, h);
    }
    
    public static LinearLayout.LayoutParams createLayoutParam(int w,int h){
      return new LinearLayout.LayoutParams(w, h);
    }
    
    public static LinearLayout.LayoutParams createLayoutParam(int w,int h,int weight){
      return new LinearLayout.LayoutParams(w, h,weight);
    }
  

  public static LinearLayout.LayoutParams createLayoutParam(boolean fillWidth,boolean fillHeight,int weight){
    int w= LinearLayout.LayoutParams.WRAP_CONTENT;
    int h= LinearLayout.LayoutParams.WRAP_CONTENT;
    if(fillWidth){
      w= LinearLayout.LayoutParams.FILL_PARENT;
    }
    if(fillHeight){
      h=LinearLayout.LayoutParams.FILL_PARENT;
    }
    return new LinearLayout.LayoutParams(w, h,weight);
  }
}

Create Linear Layout

    
//package com.akjava.lib.android.ui;

import java.io.BufferedInputStream;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class WidgetUtil {

  public static LinearLayout createLinearLayout(Context context,boolean horizontal){
    LinearLayout linear=new LinearLayout(context);
    if(!horizontal){
    linear.setOrientation(LinearLayout.VERTICAL);
    }
    return linear;
  }
  
}

This sample application shows how to use layout animation and various transformations on views.

    
 
 
package com.example.android.apis.animation;

import com.example.android.apis.R;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;

public class Transition3d extends Activity implements
        AdapterView.OnItemClickListener, View.OnClickListener {
    private ListView mPhotosList;
    private ViewGroup mContainer;
    private ImageView mImageView;

    // Names of the photos we show in the list
    private static final String[] PHOTOS_NAMES = new String[] {
            "Lyon",
            "Livermore",
            "Tahoe Pier",
            "Lake Tahoe",
            "Grand Canyon",
            "Bodie"
    };

    // Resource identifiers for the photos we want to display
    private static final int[] PHOTOS_RESOURCES = new int[] {
            R.drawable.photo1,
            R.drawable.photo2,
            R.drawable.photo3,
            R.drawable.photo4,
            R.drawable.photo5,
            R.drawable.photo6
    };

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

        setContentView(R.layout.animations_main_screen);

        mPhotosList = (ListView) findViewById(android.R.id.list);
        mImageView = (ImageView) findViewById(R.id.picture);
        mContainer = (ViewGroup) findViewById(R.id.container);

        // Prepare the ListView
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, PHOTOS_NAMES);

        mPhotosList.setAdapter(adapter);
        mPhotosList.setOnItemClickListener(this);

        // Prepare the ImageView
        mImageView.setClickable(true);
        mImageView.setFocusable(true);
        mImageView.setOnClickListener(this);

        // Since we are caching large views, we want to keep their cache
        // between each animation
        mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
    }

    private void applyRotation(int position, float start, float end) {
        // Find the center of the container
        final float centerX = mContainer.getWidth() / 2.0f;
        final float centerY = mContainer.getHeight() / 2.0f;

        // Create a new 3D rotation with the supplied parameter
        // The animation listener is used to trigger the next animation
        final Rotate3dAnimation rotation =
                new Rotate3dAnimation(start, end, centerX, centerY, 310.0f, true);
        rotation.setDuration(500);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(position));

        mContainer.startAnimation(rotation);
    }

    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        // Pre-load the image then start the animation
        mImageView.setImageResource(PHOTOS_RESOURCES[position]);
        applyRotation(position, 0, 90);
    }

    public void onClick(View v) {
        applyRotation(-1, 180, 90);
    }


    private final class DisplayNextView implements Animation.AnimationListener {
        private final int mPosition;

        private DisplayNextView(int position) {
            mPosition = position;
        }

        public void onAnimationStart(Animation animation) {
        }

        public void onAnimationEnd(Animation animation) {
            mContainer.post(new SwapViews(mPosition));
        }

        public void onAnimationRepeat(Animation animation) {
        }
    }


    private final class SwapViews implements Runnable {
        private final int mPosition;

        public SwapViews(int position) {
            mPosition = position;
        }

        public void run() {
            final float centerX = mContainer.getWidth() / 2.0f;
            final float centerY = mContainer.getHeight() / 2.0f;
            Rotate3dAnimation rotation;
            
            if (mPosition > -1) {
                mPhotosList.setVisibility(View.GONE);
                mImageView.setVisibility(View.VISIBLE);
                mImageView.requestFocus();

                rotation = new Rotate3dAnimation(90, 180, centerX, centerY, 310.0f, false);
            } else {
                mImageView.setVisibility(View.GONE);
                mPhotosList.setVisibility(View.VISIBLE);
                mPhotosList.requestFocus();

                rotation = new Rotate3dAnimation(90, 0, centerX, centerY, 310.0f, false);
            }

            rotation.setDuration(500);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());

            mContainer.startAnimation(rotation);
        }
    }

}

//layout/animations_main_screen.xml




<?xml version="1.0" encoding="utf-8"?>


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@android:id/list"
        android:persistentDrawingCache="animation|scrolling"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layoutAnimation="@anim/layout_bottom_to_top_slide" />

    <ImageView
        android:id="@+id/picture"
        android:scaleType="fitCenter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />

</FrameLayout>


package com.example.android.apis.animation;

import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.graphics.Camera;
import android.graphics.Matrix;

public class Rotate3dAnimation extends Animation {
    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private final float mDepthZ;
    private final boolean mReverse;
    private Camera mCamera;


    public Rotate3dAnimation(float fromDegrees, float toDegrees,
            float centerX, float centerY, float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
        mReverse = reverse;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();

        camera.save();
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();

        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}
Tabs that uses labels TabSpec#setIndicator(CharSequence) for indicators and views by id from a layout file TabSpec#setContent(int)
package com.example.android.apis.view;

import android.app.TabActivity;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.view.LayoutInflater;

import com.example.android.apis.R;

public class Tabs1 extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TabHost tabHost = getTabHost();
        
        LayoutInflater.from(this).inflate(R.layout.tabs1, tabHost.getTabContentView(), true);

        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("tab1")
                .setContent(R.id.view1));
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("tab2")
                .setContent(R.id.view2));
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("tab3")
                .setContent(R.id.view3));
    }
}


//layout/tabs1.xml

<?xml version="1.0" encoding="utf-8"?>


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:id="@+id/view1"
        android:background="@drawable/blue"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/tabs_1_tab_1"/>

    <TextView android:id="@+id/view2"
        android:background="@drawable/red"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/tabs_1_tab_2"/>

    <TextView android:id="@+id/view3"
        android:background="@drawable/green"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/tabs_1_tab_3"/>

</FrameLayout>
This example shows how to use cell spanning in a table layout.
package com.example.android.apis.view;

import com.example.android.apis.R;

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

/**
 * <p>This example shows how to use cell spanning in a table layout.</p>
 */
public class TableLayout12 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.table_layout_12);
    }
}

//layout/table_layout_12.xml
<?xml version="1.0" encoding="utf-8"?>


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TableRow>
        <TextView
            android:text="@string/table_layout_12_a"
            android:background="#FFFF0000"
            android:padding="3dip" />
        <TextView
            android:text="@string/table_layout_12_b"
            android:background="#FF00FF00"
            android:padding="3dip" />
        <TextView
            android:text="@string/table_layout_12_c"
            android:background="#FF0000FF"
            android:padding="3dip" />
    </TableRow>

    <TableRow>
        <TextView
            android:text="@string/table_layout_12_d"
            android:layout_span="2"
            android:gravity="center_horizontal"
            android:background="#FF0000FF"
            android:padding="3dip" />
        <TextView
            android:text="@string/table_layout_12_e"
            android:background="#FF00FF00"
            android:padding="3dip" />
    </TableRow>

    <TableRow>
        <TextView
            android:text="@string/table_layout_12_f"
            android:background="#FFFF00FF"
            android:padding="3dip" />
        <TextView
            android:text="@string/table_layout_12_g"
            android:background="#FF00FF00"
            android:padding="3dip" />
        <TextView
            android:text="@string/table_layout_12_h"
            android:background="#FFFF0000"
            android:padding="3dip" />
    </TableRow>

    <TableRow>
        <TextView
            android:text="@string/table_layout_12_a"
            android:background="#FF00FF00"
            android:padding="3dip" />
        <TextView
            android:text="@string/table_layout_12_b"
            android:layout_span="2"
            android:gravity="center_horizontal"
            android:background="#FF0000FF"
            android:padding="3dip" />
    </TableRow>

    <TableRow>
        <TextView
            android:text="@string/table_layout_12_g"
            android:layout_span="3"
            android:gravity="center_horizontal"
            android:background="#FFC0C0C0"
            android:padding="3dip" />
    </TableRow>
</TableLayout>
Demonstrates wrapping a layout in a ScrollView.
package com.example.android.apis.view;

import com.example.android.apis.R;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Button;

/**
 * Demonstrates wrapping a layout in a ScrollView.
 *
 */
public class ScrollView2 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scroll_view_2);

        LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
        for (int i = 2; i < 64; i++) {
            TextView textView = new TextView(this);
            textView.setText("Text View " + i);
            LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            layout.addView(textView, p);

            Button buttonView = new Button(this);
            buttonView.setText("Button " + i);
            layout.addView(buttonView, p);
        }
    }
}


//layout/scroll_view_2.xml

<?xml version="1.0" encoding="utf-8"?>


<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none">

    <LinearLayout
        android:id="@+id/layout"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="scroll_view_2_text_1"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="scroll_view_2_button_1"/>

    </LinearLayout>
</ScrollView>

Demonstrates using a relative layout to create a form

package com.example.android.apis.view;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

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


/**
 * Builds building a simple form using a RelativeLayout
 * 
 */
public class RelativeLayout2 extends Activity {

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


//layout/relative_layout_2.xml

<?xml version="1.0" encoding="utf-8"?>

  

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/blue"
    android:padding="10dip">

    <TextView
        android:id="@+id/label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/relative_layout_2_instructions"/>

    <EditText
        android:id="@+id/entry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_below="@id/label"/>

 
    <Button
        android:id="@+id/ok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/entry"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="10dip"
        android:text="relative_layout_2_ok" />
>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/ok"
        android:layout_alignTop="@id/ok"
        android:text="relative_layout_2_cancel" />

</RelativeLayout>

A simple layout which demonstrates stretching a view to fill the space between two other views.

package com.example.android.apis.view;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

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


/**
 * A simple layout which demonstrates stretching a view to fill the space between two other views.
 */
public class RelativeLayout1 extends Activity {

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

//layout/relative_layout_1.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- view1 goes on top -->
    <TextView
        android:id="@+id/view1"
        android:background="@drawable/red"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="relative_layout_1_top"/>

    <!-- view2 goes on the bottom -->
    <TextView
        android:id="@+id/view2"
        android:background="@drawable/green"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="relative_layout_1_bottom"/>

    <!-- view3 stretches betweeen view1 and view2 -->
    <TextView
        android:id="@+id/view3"
        android:background="@drawable/yellow"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_above="@id/view2"
        android:layout_below="@id/view1"
        android:text="relative_layout_1_center"/>

</RelativeLayout>

Demonstrates a horizontal linear layout with equally sized columns. Some columns force their height to match the parent.

package com.example.android.apis.view;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

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


/**
 * Demonstrates using match_parent within a linear layout whose size is not fixed.
 *
 */
public class LinearLayout7 extends Activity {

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

//layout/linear_layout_7.xml


<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:background="@drawable/red"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="linear_layout_7_small"/>

    <TextView
        android:background="@drawable/green"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="linear_layout_7_big"/>

    <TextView
        android:background="@drawable/blue"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="linear_layout_7_small" />

    <TextView
        android:background="@drawable/yellow"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="linear_layout_7_wrap"/>

</LinearLayout>

Demonstrates a nesting layouts to make a form

package com.example.android.apis.view;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

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


/**
 * Demonstrates building a simple form with nested LinearLayouts.
 *
 */
public class LinearLayout5 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.linear_layout_5);
    }
}
//layout/linear_layout_5.xml



<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@drawable/blue"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dip">

  
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="linear_layout_5_instructions"/>

  
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"/>


    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="linear_layout_5_cancel"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:text="linear_layout_5_ok" />

    </LinearLayout>

</LinearLayout>

Demonstrates a horizontal linear layout with equally sized columns

package com.example.android.apis.view;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

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


/**
 * Demonstrates a horizontal linear layout with equally sized columns.
 *
 */
public class LinearLayout4 extends Activity {

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

//layout/linear_layout_4.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:background="@drawable/red"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    <TextView
        android:background="@drawable/green"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    <TextView
        android:background="@drawable/blue"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    <TextView
        android:background="@drawable/yellow"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

</LinearLayout>

A simple linear layout fills the screen, with the children stacked from the top. The middle child gets allocated any extra space.

package com.example.android.apis.view;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

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


/**
 * A simple linear layout that fills the screen vertically, and the middle child is padded with extra space.
 */
public class LinearLayout3 extends Activity {

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

//layout/linear_layout_3.xml


<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!--
    Demonstrates a simple linear layout. The layout fills the screen, with the
    children stacked from the top. The middle child gets allocated any extra
    space.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@drawable/blue"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- view1 goes on top -->
    <TextView
        android:background="@drawable/box"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="linear_layout_3_top"/>

    <!-- view2 goes in the middle -->
    <TextView
        android:background="@drawable/box"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="linear_layout_3_middle"/>

    <!-- view3 goes on the bottom -->
    <TextView
        android:background="@drawable/box"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="linear_layout_3_bottom"/>

</LinearLayout>

Demonstrates a simple linear layout. The layout fills the screen, with the children stacked from the top.

package com.example.android.apis.view;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

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


/**
 * A simple linear layout that fills the screen vertically, but the children are not padded.
 */
public class LinearLayout2 extends Activity {

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

//layout/linear_layout_2.xml




<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@drawable/blue"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- view1 goes on top -->
    <TextView
        android:background="@drawable/box"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="linear_layout_2_top"/>

    <!-- view2 goes in the middle -->
    <TextView
       android:background="@drawable/box"
       android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="linear_layout_2_middle"/>

    <!-- view3 goes on the bottom -->
    <TextView
        android:background="@drawable/box"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="linear_layout_2_bottom"/>

</LinearLayout>

Demonstrates a simple linear layout. The height of the layout is the sum of its children.

package com.example.android.apis.view;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

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


/**
 * A simple linear layout where the height of the layout is the sum of its children.
 */
public class LinearLayout1 extends Activity {

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


//layout/linear_layout_1.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@drawable/blue"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <!-- view1 goes on top -->
    <TextView
        android:background="@drawable/box"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="linear_layout_1_top"/>

    <!-- view2 goes in the middle -->
    <TextView
        android:background="@drawable/box"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="linear_layout_1_middle"/>

    <!-- view3 goes on the bottom -->
    <TextView
        android:background="@drawable/box"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="linear_layout_1_bottom"/>

</LinearLayout>

Layout animation row left slide

package com.example.android.apis.view;

import com.example.android.apis.R;

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

public class LayoutAnimation7 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_animation_7);
    }
}


//layout/layout_animation_7.xml

<?xml version="1.0" encoding="utf-8"?>


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layoutAnimation="@anim/layout_animation_table"
    android:animationCache="false"
    android:clipToPadding="false"
    android:padding="12dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="1">

    <TableRow
        android:layoutAnimation="@anim/layout_animation_row_right_slide">
        <TextView
            android:gravity="right"
            android:text="@string/layout_animation_name" />
        <EditText />
    </TableRow>

    <TableRow
        android:layoutAnimation="@anim/layout_animation_row_left_slide">
        <TextView
            android:gravity="right"
            android:text="@string/layout_animation_lastname" />
        <EditText />
    </TableRow>

    <TableRow
        android:layoutAnimation="@anim/layout_animation_row_right_slide">
        <TextView
            android:gravity="right"
            android:text="@string/layout_animation_phone" />
        <EditText />
    </TableRow>

    <TableRow
        android:layoutAnimation="@anim/layout_animation_row_left_slide">
        <TextView
            android:gravity="right"
            android:text="@string/layout_animation_address" />
        <EditText android:lines="3" />
    </TableRow>
</TableLayout>

//anim/layout_animation_row_left_slide.xml

<?xml version="1.0" encoding="utf-8"?>


<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:delay="10%"
        android:animation="@anim/slide_left" />


//anim/layout_animation_row_right_slide.xml
<?xml version="1.0" encoding="utf-8"?>


<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:delay="10%"
        android:animationOrder="reverse"
        android:animation="@anim/slide_right" />
Layout wave scale
package com.example.android.apis.view;

import com.example.android.apis.R;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
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 java.util.List;

public class LayoutAnimation6 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadApps();

        setContentView(R.layout.layout_animation_6);
        GridView grid = (GridView) findViewById(R.id.grid);
        grid.setAdapter(new AppsAdapter());
    }

    private List<ResolveInfo> mApps;

    private void loadApps() {
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
    }

    public class AppsAdapter extends BaseAdapter {
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(LayoutAnimation6.this);

            ResolveInfo info = mApps.get(position % mApps.size());

            i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));
            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            final int w = (int) (36 * getResources().getDisplayMetrics().density + 0.5f);
            i.setLayoutParams(new GridView.LayoutParams(w, w));
            return i;
        }


        public final int getCount() {
            return Math.min(32, mApps.size());
        }

        public final Object getItem(int position) {
            return mApps.get(position % mApps.size());
        }

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

}

//layout/layout_animation_6.xml



<?xml version="1.0" encoding="utf-8"?>


<GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/grid"
    android:layoutAnimation="@anim/layout_wave_scale"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:verticalSpacing="10dp"

    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"

    android:gravity="center" />


//anim/layout_wave_scale.xml

<?xml version="1.0" encoding="utf-8"?>

<gridLayoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:rowDelay="75%"
        android:columnDelay="0%"
        android:directionPriority="none"
        android:animation="@anim/wave_scale" />

Layout grid inverse fade

package com.example.android.apis.view;

import com.example.android.apis.R;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
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 java.util.List;

public class LayoutAnimation5 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadApps();

        setContentView(R.layout.layout_animation_5);
        GridView grid = (GridView) findViewById(R.id.grid);
        grid.setAdapter(new AppsAdapter());
    }

    private List<ResolveInfo> mApps;

    private void loadApps() {
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
    }

    public class AppsAdapter extends BaseAdapter {
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(LayoutAnimation5.this);

            ResolveInfo info = mApps.get(position % mApps.size());

            i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));
            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            final int w = (int) (36 * getResources().getDisplayMetrics().density + 0.5f);
            i.setLayoutParams(new GridView.LayoutParams(w, w));
            return i;
        }


        public final int getCount() {
            return Math.min(32, mApps.size());
        }

        public final Object getItem(int position) {
            return mApps.get(position % mApps.size());
        }

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

}


//layout/layout_animation_5.xml

<?xml version="1.0" encoding="utf-8"?>


<GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/grid"
    android:layoutAnimation="@anim/layout_grid_inverse_fade"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"

    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"

    android:gravity="center" />


//anim/layout_grid_inverse_fade.xml

<?xml version="1.0" encoding="utf-8"?>


<gridLayoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:columnDelay="0.5"
        android:directionPriority="row"
        android:direction="right_to_left|bottom_to_top"
        android:animation="@anim/fade" />

Layout random fade

package com.example.android.apis.view;

import com.example.android.apis.R;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
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 java.util.List;

public class LayoutAnimation4 extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadApps();

        setContentView(R.layout.layout_animation_4);
        GridView grid = (GridView) findViewById(R.id.grid);
        grid.setAdapter(new AppsAdapter());

    }

    private List<ResolveInfo> mApps;

    private void loadApps() {
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
    }

    public class AppsAdapter extends BaseAdapter {
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(LayoutAnimation4.this);

            ResolveInfo info = mApps.get(position % mApps.size());

            i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));
            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            final int w = (int) (36 * getResources().getDisplayMetrics().density + 0.5f);
            i.setLayoutParams(new GridView.LayoutParams(w, w));
            return i;
        }


        public final int getCount() {
            return Math.min(32, mApps.size());
        }

        public final Object getItem(int position) {
            return mApps.get(position % mApps.size());
        }

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

//layout/layout_animation_4.xml

<?xml version="1.0" encoding="utf-8"?>


<GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/grid"
    android:layoutAnimation="@anim/layout_random_fade"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"

    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"

    android:gravity="center" />


//anim/layout_random_fade.xml

<?xml version="1.0" encoding="utf-8"?>


<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:delay="0.5"
        android:animationOrder="random"
        android:animation="@anim/fade" />

Layout bottom to top slide

package com.example.android.apis.view;

import com.example.android.apis.R;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class LayoutAnimation3 extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_animation_3);
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, mStrings));
    }

    private String[] mStrings = {
        "Bordeaux",
        "Lyon",
        "Marseille",
        "Nancy",
        "Paris",
        "Toulouse",
        "Strasbourg"
    };
}


//layout_animation_3.xml



<?xml version="1.0" encoding="utf-8"?>


<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layoutAnimation="@anim/layout_bottom_to_top_slide" />

//anim/layout_bottom_to_top_slide.xml

<?xml version="1.0" encoding="utf-8"?>


<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:delay="30%"
        android:animationOrder="reverse"
        android:animation="@anim/slide_right" />

Layout grid fade

package com.example.android.apis.view;

import com.example.android.apis.R;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
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 java.util.List;

public class LayoutAnimation1 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadApps();

        setContentView(R.layout.layout_animation_1);
        GridView grid = (GridView) findViewById(R.id.grid);
        grid.setAdapter(new LayoutAnimation1.AppsAdapter());
    }

    private List<ResolveInfo> mApps;

    private void loadApps() {
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
    }

    public class AppsAdapter extends BaseAdapter {
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(LayoutAnimation1.this);

            ResolveInfo info = mApps.get(position % mApps.size());

            i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));
            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            final int w = (int) (36 * getResources().getDisplayMetrics().density + 0.5f);
            i.setLayoutParams(new GridView.LayoutParams(w, w));
            return i;
        }


        public final int getCount() {
            return Math.min(32, mApps.size());
        }

        public final Object getItem(int position) {
            return mApps.get(position % mApps.size());
        }

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

}
//
<?xml version="1.0" encoding="utf-8"?>


<GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/grid"
    android:layoutAnimation="@anim/layout_grid_fade"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"

    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"

    android:gravity="center" />

//anim/layout_grid_fade.xml


<?xml version="1.0" encoding="utf-8"?>


<gridLayoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:rowDelay="50%"
        android:directionPriority="column"
        android:animation="@anim/fade" />

Layout align Baseline, align Right

package com.example.android.apis.view;

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


/**
 * Baseline alignment in RelativeLayout.
 */
public class Baseline6 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText android:id="@+id/anchor"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="20sp"
        android:text="baseline_6_multi_line" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/anchor"
        android:layout_alignRight="@id/anchor"
        android:text="baseline_6_baseline" />

</RelativeLayout>

Layout gravity center vertical

package com.example.android.apis.view;

import com.example.android.apis.R;

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


/**
 * Baseline alignement in LinearLayout with a center_vertical gravity. This sample shows that
 * using a center_vertical gravity disables baseline alignment.
 */
public class Baseline3 extends Activity {

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


//main.xml


<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="baseline_3_explanation" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_weight="1.0"
        android:layout_height="0dip">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="3dip"
            android:layout_gravity="center_vertical"
            android:text="baseline_3_label" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="3dip"
            android:layout_gravity="center_vertical"
            android:text="baseline_3_button" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="20sp"
            android:text="baseline_3_bigger" />

    </LinearLayout>

</LinearLayout>

 Layout gravity bottom

package com.example.android.apis.view;


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


/**
 * Baseline alignment in LinearLayout with a BOTTOM gravity.
 */
public class Baseline2 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
//main.xml


<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="3dip"
        android:layout_gravity="bottom"
        android:text="baseline_2_label" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="3dip"
        android:layout_gravity="bottom"
        android:text="baseline_2_button" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:textSize="20sp"
        android:text="baseline_2_bigger" />

</LinearLayout>

Use LayoutTransition to automate transition animations as items are hidden or shown in a container.

package com.example.android.apis.animation;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.widget.LinearLayout;
import com.example.android.apis.R;

import android.animation.AnimatorListenerAdapter;
import android.animation.Keyframe;
import android.animation.LayoutTransition;
import android.animation.PropertyValuesHolder;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

/**
 * This application demonstrates how to use LayoutTransition to automate transition animations
 * as items are hidden or shown in a container.
 */
public class LayoutAnimationsHideShow extends Activity {

    private int numButtons = 1;
    ViewGroup container = null;

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

        final CheckBox hideGoneCB = (CheckBox) findViewById(R.id.hideGoneCB);

        container = new LinearLayout(this);
        container.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));

        // Add a slew of buttons to the container. We won't add any more buttons at runtime, but
        // will just show/hide the buttons we've already created
        for (int i = 0; i < 6; ++i) {
            Button newButton = new Button(this);
            newButton.setText("Click to Hide " + i);
            container.addView(newButton);
            newButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    v.setVisibility(hideGoneCB.isChecked() ? View.GONE : View.INVISIBLE);
                }
            });
        }
        final LayoutTransition transitioner = new LayoutTransition();
        container.setLayoutTransition(transitioner);

        ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
        parent.addView(container);

        Button addButton = (Button) findViewById(R.id.addNewButton);
        addButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                for (int i = 0; i < container.getChildCount(); ++i) {
                    View view = (View) container.getChildAt(i);
                    view.setVisibility(View.VISIBLE);
                }
            }
        });

        CheckBox customAnimCB = (CheckBox) findViewById(R.id.customAnimCB);
        customAnimCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                long duration;
                if (isChecked) {
                    transitioner.setStagger(LayoutTransition.CHANGE_APPEARING, 30);
                    transitioner.setStagger(LayoutTransition.CHANGE_DISAPPEARING, 30);
                    setupAnimations(transitioner);
                    duration = 500;
                } else {
                    transitioner.setStagger(LayoutTransition.CHANGE_APPEARING, 0);
                    transitioner.setStagger(LayoutTransition.CHANGE_DISAPPEARING, 0);
                    transitioner.setAnimator(LayoutTransition.APPEARING, null);
                    transitioner.setAnimator(LayoutTransition.DISAPPEARING, null);
                    transitioner.setAnimator(LayoutTransition.CHANGE_APPEARING, null);
                    transitioner.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, null);
                    duration = 300;
                }
                transitioner.setDuration(duration);
            }
        });
    }

    private void setupAnimations(LayoutTransition transition) {
        // Changing while Adding
        PropertyValuesHolder pvhLeft =
                PropertyValuesHolder.ofInt("left", 0, 1);
        PropertyValuesHolder pvhTop =
                PropertyValuesHolder.ofInt("top", 0, 1);
        PropertyValuesHolder pvhRight =
                PropertyValuesHolder.ofInt("right", 0, 1);
        PropertyValuesHolder pvhBottom =
                PropertyValuesHolder.ofInt("bottom", 0, 1);
        PropertyValuesHolder pvhScaleX =
                PropertyValuesHolder.ofFloat("scaleX", 1f, 0f, 1f);
        PropertyValuesHolder pvhScaleY =
                PropertyValuesHolder.ofFloat("scaleY", 1f, 0f, 1f);
        final ObjectAnimator changeIn = ObjectAnimator.ofPropertyValuesHolder(
                        this, pvhLeft, pvhTop, pvhRight, pvhBottom, pvhScaleX, pvhScaleY).
                setDuration(transition.getDuration(LayoutTransition.CHANGE_APPEARING));
        transition.setAnimator(LayoutTransition.CHANGE_APPEARING, changeIn);
        changeIn.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setScaleX(1f);
                view.setScaleY(1f);
            }
        });

        // Changing while Removing
        Keyframe kf0 = Keyframe.ofFloat(0f, 0f);
        Keyframe kf1 = Keyframe.ofFloat(.9999f, 360f);
        Keyframe kf2 = Keyframe.ofFloat(1f, 0f);
        PropertyValuesHolder pvhRotation =
                PropertyValuesHolder.ofKeyframe("rotation", kf0, kf1, kf2);
        final ObjectAnimator changeOut = ObjectAnimator.ofPropertyValuesHolder(
                        this, pvhLeft, pvhTop, pvhRight, pvhBottom, pvhRotation).
                setDuration(transition.getDuration(LayoutTransition.CHANGE_DISAPPEARING));
        transition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, changeOut);
        changeOut.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotation(0f);
            }
        });

        // Adding
        ObjectAnimator animIn = ObjectAnimator.ofFloat(null, "rotationY", 90f, 0f).
                setDuration(transition.getDuration(LayoutTransition.APPEARING));
        transition.setAnimator(LayoutTransition.APPEARING, animIn);
        animIn.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotationY(0f);
            }
        });

        // Removing
        ObjectAnimator animOut = ObjectAnimator.ofFloat(null, "rotationX", 0f, 90f).
                setDuration(transition.getDuration(LayoutTransition.DISAPPEARING));
        transition.setAnimator(LayoutTransition.DISAPPEARING, animOut);
        animIn.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotationX(0f);
            }
        });

    }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/parent"
    >
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Show Buttons"
            android:id="@+id/addNewButton"
            />
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Custom Animations"
            android:id="@+id/customAnimCB"
            />
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hide (GONE)"
            android:id="@+id/hideGoneCB"
            />
    </LinearLayout>
</LinearLayout>
Use the animateLayoutChanges tag in XML to automate transition animations as items are removed from or added to a container.
package app.test;


import android.view.View;
import android.view.ViewGroup;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

/**
 * This application demonstrates how to use the animateLayoutChanges tag in XML to automate
 * transition animations as items are removed from or added to a container.
 */
public class Test extends Activity {

    private int numButtons = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final ViewGroup horizontalContainer = (ViewGroup) findViewById(R.id.horizontalContainer);
        final ViewGroup verticalContainer = (ViewGroup) findViewById(R.id.verticalContainer);

        Button addButton = (Button) findViewById(R.id.addNewButton);
        addButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Button newButton = new Button(Test.this);
                newButton.setText("Click To Remove " + (numButtons++));
                newButton.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        horizontalContainer.removeView(v);
                    }
                });
                horizontalContainer.addView(newButton, Math.min(1, horizontalContainer.getChildCount()));

                newButton = new Button(Test.this);
                newButton.setText("Click To Remove " + (numButtons++));
                newButton.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        verticalContainer.removeView(v);
                    }
                });
                verticalContainer.addView(newButton, Math.min(1, verticalContainer.getChildCount()));
            }
        });
    }

}
//main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Button"
        android:id="@+id/addNewButton"
        />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/horizontalContainer"
        android:animateLayoutChanges="true"
        />
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/verticalContainer"
        android:animateLayoutChanges="true"
        />
</LinearLayout>
A layout that arranges its children in a grid.
package com.example.android.apis.animation;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.widget.LinearLayout;
import com.example.android.apis.R;

import android.animation.AnimatorListenerAdapter;
import android.animation.Keyframe;
import android.animation.LayoutTransition;
import android.animation.PropertyValuesHolder;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

 class FixedGridLayout extends ViewGroup {
    int mCellWidth;
    int mCellHeight;

    public FixedGridLayout(Context context) {
        super(context);
    }

    public void setCellWidth(int px) {
        mCellWidth = px;
        requestLayout();
    }

    public void setCellHeight(int px) {
        mCellHeight = px;
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int cellWidthSpec = MeasureSpec.makeMeasureSpec(mCellWidth,
                MeasureSpec.AT_MOST);
        int cellHeightSpec = MeasureSpec.makeMeasureSpec(mCellHeight,
                MeasureSpec.AT_MOST);

        int count = getChildCount();
        for (int index=0; index<count; index++) {
            final View child = getChildAt(index);
            child.measure(cellWidthSpec, cellHeightSpec);
        }
        // Use the size our parents gave us, but default to a minimum size to avoid
        // clipping transitioning children
        int minCount =  count > 3 ? count : 3;
        setMeasuredDimension(resolveSize(mCellWidth * minCount, widthMeasureSpec),
                resolveSize(mCellHeight * minCount, heightMeasureSpec));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int cellWidth = mCellWidth;
        int cellHeight = mCellHeight;
        int columns = (r - l) / cellWidth;
        if (columns < 0) {
            columns = 1;
        }
        int x = 0;
        int y = 0;
        int i = 0;
        int count = getChildCount();
        for (int index=0; index<count; index++) {
            final View child = getChildAt(index);

            int w = child.getMeasuredWidth();
            int h = child.getMeasuredHeight();

            int left = x + ((cellWidth-w)/2);
            int top = y + ((cellHeight-h)/2);

            child.layout(left, top, left+w, top+h);
            if (i >= (columns-1)) {
                // advance to next row
                i = 0;
                x = 0;
                y += cellHeight;
            } else {
                i++;
                x += cellWidth;
            }
        }
    }
}


/**
 * This application demonstrates how to use LayoutTransition to automate transition animations
 * as items are removed from or added to a container.
 */
public class Test extends Activity {

    private int numButtons = 1;
    ViewGroup container = null;
    Animator defaultAppearingAnim, defaultDisappearingAnim;
    Animator defaultChangingAppearingAnim, defaultChangingDisappearingAnim;
    Animator customAppearingAnim, customDisappearingAnim;
    Animator customChangingAppearingAnim, customChangingDisappearingAnim;
    Animator currentAppearingAnim, currentDisappearingAnim;
    Animator currentChangingAppearingAnim, currentChangingDisappearingAnim;

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

        container = new FixedGridLayout(this);
        container.setClipChildren(false);
        ((FixedGridLayout)container).setCellHeight(50);
        ((FixedGridLayout)container).setCellWidth(200);
        final LayoutTransition transitioner = new LayoutTransition();
        container.setLayoutTransition(transitioner);
        defaultAppearingAnim = transitioner.getAnimator(LayoutTransition.APPEARING);
        defaultDisappearingAnim =
                transitioner.getAnimator(LayoutTransition.DISAPPEARING);
        defaultChangingAppearingAnim =
                transitioner.getAnimator(LayoutTransition.CHANGE_APPEARING);
        defaultChangingDisappearingAnim =
                transitioner.getAnimator(LayoutTransition.CHANGE_DISAPPEARING);
        createCustomAnimations(transitioner);
        currentAppearingAnim = defaultAppearingAnim;
        currentDisappearingAnim = defaultDisappearingAnim;
        currentChangingAppearingAnim = defaultChangingAppearingAnim;
        currentChangingDisappearingAnim = defaultChangingDisappearingAnim;

        ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
        parent.addView(container);
        parent.setClipChildren(false);
        Button addButton = (Button) findViewById(R.id.addNewButton);
        addButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Button newButton = new Button(Test.this);
                newButton.setText("Click to Delete " + (numButtons++));
                newButton.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        container.removeView(v);
                    }
                });
                container.addView(newButton, Math.min(1, container.getChildCount()));
            }
        });

        CheckBox customAnimCB = (CheckBox) findViewById(R.id.customAnimCB);
        customAnimCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setupTransition(transitioner);
            }
        });

        // Check for disabled animations
        CheckBox appearingCB = (CheckBox) findViewById(R.id.appearingCB);
        appearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setupTransition(transitioner);
            }
        });
        CheckBox disappearingCB = (CheckBox) findViewById(R.id.disappearingCB);
        disappearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setupTransition(transitioner);
            }
        });
        CheckBox changingAppearingCB = (CheckBox) findViewById(R.id.changingAppearingCB);
        changingAppearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setupTransition(transitioner);
            }
        });
        CheckBox changingDisappearingCB = (CheckBox) findViewById(R.id.changingDisappearingCB);
        changingDisappearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setupTransition(transitioner);
            }
        });
    }

    private void setupTransition(LayoutTransition transition) {
        CheckBox customAnimCB = (CheckBox) findViewById(R.id.customAnimCB);
        CheckBox appearingCB = (CheckBox) findViewById(R.id.appearingCB);
        CheckBox disappearingCB = (CheckBox) findViewById(R.id.disappearingCB);
        CheckBox changingAppearingCB = (CheckBox) findViewById(R.id.changingAppearingCB);
        CheckBox changingDisappearingCB = (CheckBox) findViewById(R.id.changingDisappearingCB);
        transition.setAnimator(LayoutTransition.APPEARING, appearingCB.isChecked() ?
                (customAnimCB.isChecked() ? customAppearingAnim : defaultAppearingAnim) : null);
        transition.setAnimator(LayoutTransition.DISAPPEARING, disappearingCB.isChecked() ?
                (customAnimCB.isChecked() ? customDisappearingAnim : defaultDisappearingAnim) : null);
        transition.setAnimator(LayoutTransition.CHANGE_APPEARING, changingAppearingCB.isChecked() ?
                (customAnimCB.isChecked() ? customChangingAppearingAnim :
                        defaultChangingAppearingAnim) : null);
        transition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING,
                changingDisappearingCB.isChecked() ?
                (customAnimCB.isChecked() ? customChangingDisappearingAnim :
                        defaultChangingDisappearingAnim) : null);
    }

    private void createCustomAnimations(LayoutTransition transition) {
        // Changing while Adding
        PropertyValuesHolder pvhLeft =
                PropertyValuesHolder.ofInt("left", 0, 1);
        PropertyValuesHolder pvhTop =
                PropertyValuesHolder.ofInt("top", 0, 1);
        PropertyValuesHolder pvhRight =
                PropertyValuesHolder.ofInt("right", 0, 1);
        PropertyValuesHolder pvhBottom =
                PropertyValuesHolder.ofInt("bottom", 0, 1);
        PropertyValuesHolder pvhScaleX =
                PropertyValuesHolder.ofFloat("scaleX", 1f, 0f, 1f);
        PropertyValuesHolder pvhScaleY =
                PropertyValuesHolder.ofFloat("scaleY", 1f, 0f, 1f);
        customChangingAppearingAnim = ObjectAnimator.ofPropertyValuesHolder(
                        this, pvhLeft, pvhTop, pvhRight, pvhBottom, pvhScaleX, pvhScaleY).
                setDuration(transition.getDuration(LayoutTransition.CHANGE_APPEARING));
        customChangingAppearingAnim.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setScaleX(1f);
                view.setScaleY(1f);
            }
        });

        // Changing while Removing
        Keyframe kf0 = Keyframe.ofFloat(0f, 0f);
        Keyframe kf1 = Keyframe.ofFloat(.9999f, 360f);
        Keyframe kf2 = Keyframe.ofFloat(1f, 0f);
        PropertyValuesHolder pvhRotation =
                PropertyValuesHolder.ofKeyframe("rotation", kf0, kf1, kf2);
        customChangingDisappearingAnim = ObjectAnimator.ofPropertyValuesHolder(
                        this, pvhLeft, pvhTop, pvhRight, pvhBottom, pvhRotation).
                setDuration(transition.getDuration(LayoutTransition.CHANGE_DISAPPEARING));
        customChangingDisappearingAnim.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotation(0f);
            }
        });

        // Adding
        customAppearingAnim = ObjectAnimator.ofFloat(null, "rotationY", 90f, 0f).
                setDuration(transition.getDuration(LayoutTransition.APPEARING));
        customAppearingAnim.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotationY(0f);
            }
        });

        // Removing
        customDisappearingAnim = ObjectAnimator.ofFloat(null, "rotationX", 0f, 90f).
                setDuration(transition.getDuration(LayoutTransition.DISAPPEARING));
        customDisappearingAnim.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotationX(0f);
            }
        });

    }
}


//main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/parent"
    >
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add Button"
            android:id="@+id/addNewButton"
            />
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Custom Animations"
            android:id="@+id/customAnimCB"
            />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Appearing Animation"
            android:id="@+id/appearingCB"
            />
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Disappearing Animation"
            android:id="@+id/disappearingCB"
            />
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Changing/Appearing Animation"
            android:id="@+id/changingAppearingCB"
            />
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Changing/Disappearing Animation"
            android:id="@+id/changingDisappearingCB"
            />
    </LinearLayout>
</LinearLayout>

   
extends ViewGroup to do layout
package app.test;


import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Picture;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

public class Test extends GraphicsActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new SampleView(this));
    }

    private static class SampleView extends View {
        private Bitmap mBitmap;
        private Bitmap mBitmap2;
        private Bitmap mBitmap3;
        private Shader mShader;

        private static void drawIntoBitmap(Bitmap bm) {
            float x = bm.getWidth();
            float y = bm.getHeight();
            Canvas c = new Canvas(bm);
            Paint p = new Paint();
            p.setAntiAlias(true);

            p.setAlpha(0x80);
            c.drawCircle(x/2, y/2, x/2, p);

            p.setAlpha(0x30);
            p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
            p.setTextSize(60);
            p.setTextAlign(Paint.Align.CENTER);
            Paint.FontMetrics fm = p.getFontMetrics();
            c.drawText("Alpha", x/2, (y-fm.ascent)/2, p);
        }

        public SampleView(Context context) {
            super(context);
            setFocusable(true);

            InputStream is = context.getResources().openRawResource(R.drawable.icon);
            mBitmap = BitmapFactory.decodeStream(is);
            mBitmap2 = mBitmap.extractAlpha();
            mBitmap3 = Bitmap.createBitmap(200, 200, Bitmap.Config.ALPHA_8);
            drawIntoBitmap(mBitmap3);

            mShader = new LinearGradient(0, 0, 100, 70, new int[] {
                                         Color.RED, Color.GREEN, Color.BLUE },
                                         null, Shader.TileMode.MIRROR);
        }

        @Override protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.WHITE);

            Paint p = new Paint();
            float y = 10;

            p.setColor(Color.RED);
            canvas.drawBitmap(mBitmap, 10, y, p);
            y += mBitmap.getHeight() + 10;
            canvas.drawBitmap(mBitmap2, 10, y, p);
            y += mBitmap2.getHeight() + 10;
            p.setShader(mShader);
            canvas.drawBitmap(mBitmap3, 10, y, p);
        }
    }
}
class GraphicsActivity extends Activity {
    // set to true to test Picture
    private static final boolean TEST_PICTURE = false;

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

    @Override
    public void setContentView(View view) {
        if (TEST_PICTURE) {
            ViewGroup vg = new PictureLayout(this);
            vg.addView(view);
            view = vg;
        }

        super.setContentView(view);
    }
}
class PictureLayout extends ViewGroup {
    private final Picture mPicture = new Picture();

    public PictureLayout(Context context) {
        super(context);
    }

    public PictureLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void addView(View child) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child);
    }

    @Override
    public void addView(View child, int index) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, index);
    }

    @Override
    public void addView(View child, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, params);
    }

    @Override
    public void addView(View child, int index, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, index, params);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int count = getChildCount();

        int maxHeight = 0;
        int maxWidth = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }

        maxWidth += getPaddingLeft() + getPaddingRight();
        maxHeight += getPaddingTop() + getPaddingBottom();

        Drawable drawable = getBackground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

        setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
                resolveSize(maxHeight, heightMeasureSpec));
    }

    private void drawPict(Canvas canvas, int x, int y, int w, int h,
                          float sx, float sy) {
        canvas.save();
        canvas.translate(x, y);
        canvas.clipRect(0, 0, w, h);
        canvas.scale(0.5f, 0.5f);
        canvas.scale(sx, sy, w, h);
        canvas.drawPicture(mPicture);
        canvas.restore();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
        mPicture.endRecording();

        int x = getWidth()/2;
        int y = getHeight()/2;

        if (false) {
            canvas.drawPicture(mPicture);
        } else {
            drawPict(canvas, 0, 0, x, y,  1,  1);
            drawPict(canvas, x, 0, x, y, -1,  1);
            drawPict(canvas, 0, y, x, y,  1, -1);
            drawPict(canvas, x, y, x, y, -1, -1);
        }
    }

    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        location[0] = getLeft();
        location[1] = getTop();
        dirty.set(0, 0, getWidth(), getHeight());
        return getParent();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = super.getChildCount();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final int childLeft = getPaddingLeft();
                final int childTop = getPaddingTop();
                child.layout(childLeft, childTop,
                        childLeft + child.getMeasuredWidth(),
                        childTop + child.getMeasuredHeight());

            }
        }
    }
}

Layout Animation

    
package app.test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

 class LayoutAnimationActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_layout);
        setupListView();
    }
    private void setupListView()
    {
        String[] listItems = new String[] {
              "Item 1", "Item 2", "Item 3",
              "Item 4", "Item 5", "Item 6",
        };
        
        ArrayAdapter<String> listItemAdapter = 
           new ArrayAdapter<String>(this
                   ,android.R.layout.simple_list_item_1
                   ,listItems);
        ListView lv = (ListView)this.findViewById(R.id.list_view_id);
        lv.setAdapter(listItemAdapter);
    }
}


public class Test extends Activity 
{
  Menu myMenu = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
      super.onCreateOptionsMenu(menu);
      this.myMenu = menu;
      MenuInflater mi = this.getMenuInflater();
      mi.inflate(R.menu.main_menu,menu);
      return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
      try
      {
        handleMenus(item);
      }
      catch(Throwable t)
      {
        throw new RuntimeException("error",t);
      }
      return true;
    }
    private void handleMenus(MenuItem item)
    {
    this.appendMenuItemText(item);
    if (item.getItemId() == R.id.menu_clear)
    {
      this.emptyText();
    }
    else if (item.getItemId() == R.id.menu_list_animation)
    {
      Intent intent = new Intent(this, LayoutAnimationActivity.class);
      startActivity(intent);
    }
    }
    
    private TextView getTextView()
    {
         TextView tv = 
           (TextView)this.findViewById(R.id.textViewId);
         return tv;
    }
    public void appendText(String text)
    {
         TextView tv = 
           (TextView)this.findViewById(R.id.textViewId);
         tv.setText(tv.getText() + text);
    }
    public void appendMenuItemText(MenuItem menuItem)
    {
      String title = menuItem.getTitle().toString();
         TextView tv = 
           (TextView)this.findViewById(R.id.textViewId);
         tv.setText(tv.getText() + "\n" + title + ":" + menuItem.getItemId());
    }
    private void emptyText()
    {
         TextView tv = 
           (TextView)this.findViewById(R.id.textViewId);
         tv.setText("");
    }
    
}
//main.xml


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

<TextView android:id="@+id/textViewId"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Click on Menu to start the animation activity"
    />
    
</LinearLayout>

//list_layout.xml


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

    <ListView
        android:id="@+id/list_view_id"
        android:persistentDrawingCache="animation|scrolling"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layoutAnimation="@anim/list_layout_controller" />
        />
</LinearLayout>
//main_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- This group uses the default category. -->
    <group android:id="@+id/menuGroup_Main">
    
        <item android:id="@+id/menu_list_animation"
            android:orderInCategory="1"
            android:title="Animate List" />
            
        <item android:id="@+id/menu_clear"
            android:orderInCategory="10"
            android:title="clear" />
    </group>
</menu>

Layout input form

    
package app.test;

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

public class Test extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
      }
}

//main.xml


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

  <TableRow>
    <TextView android:text="First Name:"
        android:layout_width="wrap_content"  android:layout_height="wrap_content" />

    <EditText android:text="Edgar"
        android:layout_width="wrap_content"  android:layout_height="wrap_content" />
  </TableRow>

  <TableRow>
    <TextView android:text="Last Name:"
        android:layout_width="wrap_content"  android:layout_height="wrap_content" />

    <EditText android:text="Poe"
        android:layout_width="wrap_content"  android:layout_height="wrap_content" />
  </TableRow>

</TableLayout>

Layout input form

    
package app.test;

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

public class Test extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
      }
}

//main.xml


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

  <TableRow>
    <TextView android:text="First Name:"
        android:layout_width="wrap_content"  android:layout_height="wrap_content" />

    <EditText android:text="Edgar"
        android:layout_width="wrap_content"  android:layout_height="wrap_content" />
  </TableRow>

  <TableRow>
    <TextView android:text="Last Name:"
        android:layout_width="wrap_content"  android:layout_height="wrap_content" />

    <EditText android:text="Poe"
        android:layout_width="wrap_content"  android:layout_height="wrap_content" />
  </TableRow>

</TableLayout>

Using two layout xml file for one Activity

    

package app.test;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class Test extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout layoutMain = new LinearLayout(this);
    layoutMain.setOrientation(LinearLayout.HORIZONTAL);
    setContentView(layoutMain);
    LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    RelativeLayout layoutLeft = (RelativeLayout) inflate.inflate(
        R.layout.main, null);
    RelativeLayout layoutRight = (RelativeLayout) inflate.inflate(
        R.layout.row, null);

    RelativeLayout.LayoutParams relParam = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutMain.addView(layoutLeft, 100, 100);
    layoutMain.addView(layoutRight, relParam);
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/left"
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <TextView android:id="@+id/view1" android:background="@drawable/icon"
    android:layout_width="fill_parent"
    android:layout_height="50px" android:text="1" />
  <TextView android:id="@+id/view2"
    android:background="@drawable/icon"
    android:layout_width="fill_parent"
    android:layout_height="50px" android:layout_below="@id/view1"
    android:text="2" />
</RelativeLayout>

//row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/right"
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">


  <TextView android:id="@+id/right_view1"
    android:background="@drawable/icon" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="3" />
  <TextView android:id="@+id/right_view2"
    android:background="@drawable/icon"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/right_view1" android:text="4" />
</RelativeLayout>

Layout widget with code only

    

package app.test;

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

public class Test extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    super.onCreate(icicle);
    TextView HelloWorldTextView = new TextView(this);
    HelloWorldTextView.setText("Hello World!");
    setContentView(HelloWorldTextView);
  }
}

Set Layout Parameters in your code

    

package app.test;

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

public class Test extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        LayoutParams params = 
            new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        TextView tv = new TextView(this);
        tv.setText("This is a TextView");
        tv.setLayoutParams(params);
        
        Button btn = new Button(this);
        btn.setText("This is a Button");
        btn.setLayoutParams(params);
                        
        layout.addView(tv);

        layout.addView(btn);
        LinearLayout.LayoutParams layoutParam = 
            new LinearLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT );
                       
        this.addContentView(layout, layoutParam);    
    }
}

//main.xml

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

Layout Orientation

    

<?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"
    >
<EditText
    android:id="@+id/txtField1"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    />
<EditText  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    />
</LinearLayout>
Using static string in layout xml file from strings.xml
package app.test;

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

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

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<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="This is my first Android Application!" />

<Button
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="And this is a clickable button!" />
    
</LinearLayout>
//strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">HelloWorld</string>
</resources>

res\layout\main.xml

    
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>




//res\layout-land\main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>
Using LayoutInflater
package com.commonsware.android.fancylists.six;

import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;

public class RateListDemo extends ListActivity {
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "consectetuer", "adipiscing", "elit", "morbi", "vel",
          "ligula", "vitae", "arcu", "aliquet", "mollis",
          "etiam", "vel", "erat", "placerat", "ante",
          "porttitor", "sodales", "pellentesque", "augue",
          "purus"};
  
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    
    ArrayList<RowModel> list=new ArrayList<RowModel>();
    
    for (String s : items) {
      list.add(new RowModel(s));
    }
    
    setListAdapter(new RatingAdapter(list));
  }
  
  private RowModel getModel(int position) {
    return(((RatingAdapter)getListAdapter()).getItem(position));
  }
  
  class RatingAdapter extends ArrayAdapter<RowModel> {
    RatingAdapter(ArrayList<RowModel> list) {
      super(RateListDemo.this, R.layout.row, list);
    }
    
    public View getView(int position, View convertView,
                        ViewGroup parent) {
      View row=convertView;
      ViewWrapper wrapper;
      RatingBar rate;                  
                          
      if (row==null) {    
        LayoutInflater inflater=getLayoutInflater();
        
        row=inflater.inflate(R.layout.row, parent, false);
        wrapper=new ViewWrapper(row);
        row.setTag(wrapper);
        rate=wrapper.getRatingBar();
        
        RatingBar.OnRatingBarChangeListener l=
                    new RatingBar.OnRatingBarChangeListener() {
          public void onRatingChanged(RatingBar ratingBar,
                                        float rating,
                                        boolean fromTouch)  {
            Integer myPosition=(Integer)ratingBar.getTag();
            RowModel model=getModel(myPosition);
            
            model.rating=rating;
          
            LinearLayout parent=(LinearLayout)ratingBar.getParent();
            TextView label=(TextView)parent.findViewById(R.id.label);
        
            label.setText(model.toString());
          }
        };
        
        rate.setOnRatingBarChangeListener(l);
      }
      else {
        wrapper=(ViewWrapper)row.getTag();
        rate=wrapper.getRatingBar();
      }

      RowModel model=getModel(position);
      
      wrapper.getLabel().setText(model.toString());
      rate.setTag(new Integer(position));
      rate.setRating(model.rating);
      
      return(row);
    }
  }
  
  class RowModel {
    String label;
    float rating=2.0f;
    
    RowModel(String label) {
      this.label=label;
    }
    
    public String toString() {
      if (rating>=3.0) {
        return(label.toUpperCase());
      }
      
      return(label);
    }
  }
}



package com.commonsware.android.fancylists.six;

import android.view.View;
import android.widget.RatingBar;
import android.widget.TextView;

class ViewWrapper {
  View base;
  RatingBar rate=null;
  TextView label=null;
  
  ViewWrapper(View base) {
    this.base=base;
  }
  
  RatingBar getRatingBar() {
    if (rate==null) {
      rate=(RatingBar)base.findViewById(R.id.rate);
    }
    
    return(rate);
  }
  
  TextView getLabel() {
    if (label==null) {
      label=(TextView)base.findViewById(R.id.label);
    }
    
    return(label);
  }
}


//res\layout\row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
>
  <RatingBar
    android:id="@+id/rate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:numStars="3"
    android:stepSize="1"
    android:rating="2" />
  <TextView
    android:id="@+id/label"
    android:paddingLeft="2px"
    android:paddingRight="2px"
    android:paddingTop="2px"
    android:textSize="40sp"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
</LinearLayout>
Using more than one layout xml
package app.test;

import java.util.HashMap;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

class Provider extends ContentProvider {
  private static final String DATABASE_NAME = "constants.db";
  private static final int CONSTANTS = 1;
  private static final int CONSTANT_ID = 2;
  private static final UriMatcher MATCHER;
  private static HashMap<String, String> CONSTANTS_LIST_PROJECTION;

  public static final class Constants implements BaseColumns {
    public static final Uri CONTENT_URI = Uri
        .parse("content://com.commonsware.android.constants.Provider/constants");
    public static final String DEFAULT_SORT_ORDER = "title";
    public static final String TITLE = "title";
    public static final String VALUE = "value";
  }

  static {
    MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
    MATCHER.addURI("com.commonsware.android.constants.Provider",
        "constants", CONSTANTS);
    MATCHER.addURI("com.commonsware.android.constants.Provider",
        "constants/#", CONSTANT_ID);

    CONSTANTS_LIST_PROJECTION = new HashMap<String, String>();
    CONSTANTS_LIST_PROJECTION.put(Provider.Constants._ID,
        Provider.Constants._ID);
    CONSTANTS_LIST_PROJECTION.put(Provider.Constants.TITLE,
        Provider.Constants.TITLE);
    CONSTANTS_LIST_PROJECTION.put(Provider.Constants.VALUE,
        Provider.Constants.VALUE);
  }

  public String getDbName() {
    return (DATABASE_NAME);
  }

  public int getDbVersion() {
    return (1);
  }

  private class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(Context context) {
      super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      Cursor c = db
          .rawQuery(
              "SELECT name FROM sqlite_master WHERE type='table' AND name='constants'",
              null);

      try {
        if (c.getCount() == 0) {
          db.execSQL("CREATE TABLE constants (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, value REAL);");

          ContentValues cv = new ContentValues();

          cv.put(Constants.TITLE, "Gravity, Death Star I");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_DEATH_STAR_I);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Earth");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_EARTH);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Jupiter");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_JUPITER);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Mars");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_MARS);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Mercury");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_MERCURY);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Moon");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_MOON);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Neptune");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_NEPTUNE);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Pluto");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_PLUTO);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Saturn");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_SATURN);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Sun");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_SUN);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, The Island");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_THE_ISLAND);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Uranus");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_URANUS);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Venus");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_VENUS);
          db.insert("constants", getNullColumnHack(), cv);
        }
      } finally {
        c.close();
      }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      android.util.Log.w("Constants",
          "Upgrading database, which will destroy all old data");
      db.execSQL("DROP TABLE IF EXISTS constants");
      onCreate(db);
    }
  }

  private SQLiteDatabase db;

  @Override
  public boolean onCreate() {
    db = (new DatabaseHelper(getContext())).getWritableDatabase();

    return (db == null) ? false : true;
  }

  @Override
  public Cursor query(Uri url, String[] projection, String selection,
      String[] selectionArgs, String sort) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    qb.setTables(getTableName());

    if (isCollectionUri(url)) {
      qb.setProjectionMap(getDefaultProjection());
    } else {
      qb.appendWhere(getIdColumnName() + "="
          + url.getPathSegments().get(1));
    }

    String orderBy;

    if (TextUtils.isEmpty(sort)) {
      orderBy = getDefaultSortOrder();
    } else {
      orderBy = sort;
    }

    Cursor c = qb.query(db, projection, selection, selectionArgs, null,
        null, orderBy);
    c.setNotificationUri(getContext().getContentResolver(), url);
    return c;
  }

  @Override
  public String getType(Uri url) {
    if (isCollectionUri(url)) {
      return (getCollectionType());
    }

    return (getSingleType());
  }

  @Override
  public Uri insert(Uri url, ContentValues initialValues) {
    long rowID;
    ContentValues values;

    if (initialValues != null) {
      values = new ContentValues(initialValues);
    } else {
      values = new ContentValues();
    }

    if (!isCollectionUri(url)) {
      throw new IllegalArgumentException("Unknown URL " + url);
    }

    for (String colName : getRequiredColumns()) {
      if (values.containsKey(colName) == false) {
        throw new IllegalArgumentException("Missing column: " + colName);
      }
    }

    populateDefaultValues(values);

    rowID = db.insert(getTableName(), getNullColumnHack(), values);
    if (rowID > 0) {
      Uri uri = ContentUris.withAppendedId(getContentUri(), rowID);
      getContext().getContentResolver().notifyChange(uri, null);
      return uri;
    }

    throw new SQLException("Failed to insert row into " + url);
  }

  @Override
  public int delete(Uri url, String where, String[] whereArgs) {
    int count;
    long rowId = 0;

    if (isCollectionUri(url)) {
      count = db.delete(getTableName(), where, whereArgs);
    } else {
      String segment = url.getPathSegments().get(1);
      rowId = Long.parseLong(segment);
      count = db.delete(
          getTableName(),
          getIdColumnName()
              + "="
              + segment
              + (!TextUtils.isEmpty(where) ? " AND (" + where
                  + ')' : ""), whereArgs);
    }

    getContext().getContentResolver().notifyChange(url, null);
    return count;
  }

  @Override
  public int update(Uri url, ContentValues values, String where,
      String[] whereArgs) {
    int count;

    if (isCollectionUri(url)) {
      count = db.update(getTableName(), values, where, whereArgs);
    } else {
      String segment = url.getPathSegments().get(1);
      count = db.update(
          getTableName(),
          values,
          getIdColumnName()
              + "="
              + segment
              + (!TextUtils.isEmpty(where) ? " AND (" + where
                  + ')' : ""), whereArgs);
    }

    getContext().getContentResolver().notifyChange(url, null);
    return count;
  }

  private boolean isCollectionUri(Uri url) {
    return (MATCHER.match(url) == CONSTANTS);
  }

  private HashMap<String, String> getDefaultProjection() {
    return (CONSTANTS_LIST_PROJECTION);
  }

  private String getTableName() {
    return ("constants");
  }

  private String getIdColumnName() {
    return ("_id");
  }

  private String getDefaultSortOrder() {
    return ("title");
  }

  private String getCollectionType() {
    return ("vnd.android.cursor.dir/vnd.commonsware.constant");
  }

  private String getSingleType() {
    return ("vnd.android.cursor.item/vnd.commonsware.constant");
  }

  private String[] getRequiredColumns() {
    return (new String[] { "title" });
  }

  private void populateDefaultValues(ContentValues values) {
    Long now = Long.valueOf(System.currentTimeMillis());
    Resources r = Resources.getSystem();

    if (values.containsKey(Provider.Constants.VALUE) == false) {
      values.put(Provider.Constants.VALUE, 0.0f);
    }
  }

  private String getNullColumnHack() {
    return ("title");
  }

  private Uri getContentUri() {
    return (Provider.Constants.CONTENT_URI);
  }
}

public class Test extends ListActivity {
  private static final int ADD_ID = Menu.FIRST + 1;
  private static final int EDIT_ID = Menu.FIRST + 2;
  private static final int DELETE_ID = Menu.FIRST + 3;
  private static final int CLOSE_ID = Menu.FIRST + 4;
  private static final String[] PROJECTION = new String[] {
      Provider.Constants._ID, Provider.Constants.TITLE,
      Provider.Constants.VALUE };
  private Cursor constantsCursor;

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

    constantsCursor = managedQuery(Provider.Constants.CONTENT_URI,
        PROJECTION, null, null, null);

    ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.row,
        constantsCursor, new String[] { Provider.Constants.TITLE,
            Provider.Constants.VALUE }, new int[] { R.id.title,
            R.id.value });

    setListAdapter(adapter);
    registerForContextMenu(getListView());
  }

  @Override
  public void onDestroy() {
    super.onDestroy();

    constantsCursor.close();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(Menu.NONE, ADD_ID, Menu.NONE, "Add").setIcon(R.drawable.icon)
        .setAlphabeticShortcut('a');
    menu.add(Menu.NONE, CLOSE_ID, Menu.NONE, "Close")
        .setIcon(R.drawable.icon).setAlphabeticShortcut('c');

    return (super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case ADD_ID:
      add();
      return (true);

    case CLOSE_ID:
      finish();
      return (true);
    }

    return (super.onOptionsItemSelected(item));
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
      ContextMenu.ContextMenuInfo menuInfo) {
    menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete")
        .setIcon(R.drawable.icon).setAlphabeticShortcut('d');
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case DELETE_ID:
      AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
          .getMenuInfo();

      delete(info.id);
      return (true);
    }

    return (super.onOptionsItemSelected(item));
  }

  private void add() {
    LayoutInflater inflater = LayoutInflater.from(this);
    View addView = inflater.inflate(R.layout.add_edit, null);
    final DialogWrapper wrapper = new DialogWrapper(addView);

    new AlertDialog.Builder(this)
        .setTitle(R.string.add_title)
        .setView(addView)
        .setPositiveButton(R.string.ok,
            new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog,
                  int whichButton) {
                processAdd(wrapper);
              }
            })
        .setNegativeButton(R.string.cancel,
            new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog,
                  int whichButton) {
                // ignore, just dismiss
              }
            }).show();
  }

  private void delete(final long rowId) {
    if (rowId > 0) {
      new AlertDialog.Builder(this)
          .setTitle(R.string.delete_title)
          .setPositiveButton(R.string.ok,
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,
                    int whichButton) {
                  processDelete(rowId);
                }
              })
          .setNegativeButton(R.string.cancel,
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,
                    int whichButton) {
                  // ignore, just dismiss
                }
              }).show();
    }
  }

  private void processAdd(DialogWrapper wrapper) {
    ContentValues values = new ContentValues(2);

    values.put(Provider.Constants.TITLE, wrapper.getTitle());
    values.put(Provider.Constants.VALUE, wrapper.getValue());

    getContentResolver().insert(Provider.Constants.CONTENT_URI, values);
    constantsCursor.requery();
  }

  private void processDelete(long rowId) {
    Uri uri = ContentUris.withAppendedId(Provider.Constants.CONTENT_URI,
        rowId);
    getContentResolver().delete(uri, null, null);
    constantsCursor.requery();
  }

  class DialogWrapper {
    EditText titleField = null;
    EditText valueField = null;
    View base = null;

    DialogWrapper(View base) {
      this.base = base;
      valueField = (EditText) base.findViewById(R.id.value);
    }

    String getTitle() {
      return (getTitleField().getText().toString());
    }

    float getValue() {
      return (new Float(getValueField().getText().toString())
          .floatValue());
    }

    private EditText getTitleField() {
      if (titleField == null) {
        titleField = (EditText) base.findViewById(R.id.title);
      }

      return (titleField);
    }

    private EditText getValueField() {
      if (valueField == null) {
        valueField = (EditText) base.findViewById(R.id.value);
      }

      return (valueField);
    }
  }
}

//main.xml

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

//add_edit.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
  <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      >
    <TextView
        android:text="Display Name:"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        />
    <EditText
        android:id="@+id/title"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_alignParentRight="true"
        />
  </LinearLayout>
  <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      >
    <TextView
        android:text="Value:"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        />
    <EditText
        android:id="@+id/value"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_alignParentRight="true"
        />
  </LinearLayout>
</LinearLayout>

//row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <TextView
      android:id="@+id/title"
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      />
  <TextView
      android:id="@+id/value"
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentRight="true"
      />
</RelativeLayout>

//strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ConstantsBrowser</string>
    <string name="ok">OK</string>
    <string name="cancel">Cancel</string>
    <string name="add_title">Add Constant</string>
    <string name="delete_title">Delete Constant: Are You Sure?</string>
</resources>

Set layout alignment base line

    

package app.test;

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

public class Test extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
  }
}

//main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:padding="5px">
  <TextView android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="URL:"
    android:layout_alignBaseline="@+id/entry"
    android:layout_alignParentLeft="true"/>
  <EditText
    android:id="@id/entry"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/label"
    android:layout_alignParentTop="true"/>
  <Button
    android:id="@+id/ok"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/entry"
    android:layout_alignRight="@id/entry"
    android:text="OK" />
  <Button
    android:id="@+id/cancel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@id/ok"
    android:layout_alignTop="@id/ok"
    android:text="Cancel" />
</RelativeLayout>

Table layout inside a Linear layout

    


package app.test;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Test extends Activity {
  private EditText lat;
  private EditText lon;
  
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    
    Button btn=(Button)findViewById(R.id.map);
    lat=(EditText)findViewById(R.id.lat);
    lon=(EditText)findViewById(R.id.lon);
    
    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        String _lat=lat.getText().toString();
        String _lon=lon.getText().toString();
        Uri uri=Uri.parse("geo:"+_lat+","+_lon);
        
        startActivity(new Intent(Intent.ACTION_VIEW, uri));
      }
    });
  }
}

//main.cml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TableLayout
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:stretchColumns="1,2"
  >
    <TableRow>
      <TextView
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:paddingLeft="2dip"
        android:paddingRight="4dip"
        android:text="Location:"
      />
      <EditText android:id="@+id/lat"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:cursorVisible="true"
        android:editable="true"
        android:singleLine="true"
        android:layout_weight="1"
      />
      <EditText android:id="@+id/lon"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:cursorVisible="true"
        android:editable="true"
        android:singleLine="true"
        android:layout_weight="1"
      />
    </TableRow>
  </TableLayout>
  <Button android:id="@+id/map"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:text="Show Me!"
  />
</LinearLayout>

extends FrameLayout

    

package app.test;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

class TextImageButton extends FrameLayout {
  private ImageView imageView;
  private TextView textView;

  public TextImageButton(Context context) {
    this(context, null);
  }

  public TextImageButton(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public TextImageButton(Context context, AttributeSet attrs, int defaultStyle) {
    super(context, attrs, defaultStyle);
    imageView = new ImageView(context, attrs, defaultStyle);
    textView = new TextView(context, attrs, defaultStyle);
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
        LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    this.addView(imageView, params);
    this.addView(textView, params);
    setClickable(true);
    setFocusable(true);
    setBackgroundResource(android.R.drawable.btn_default);
    if (imageView.getDrawable() != null) {
      textView.setVisibility(View.GONE);
      imageView.setVisibility(View.VISIBLE);
    } else {
      textView.setVisibility(View.VISIBLE);
      imageView.setVisibility(View.GONE);
    }
  }

  public void setText(CharSequence text) {
    textView.setVisibility(View.VISIBLE);
    imageView.setVisibility(View.GONE);
    textView.setText(text);
  }

  public void setImageResource(int resId) {
    textView.setVisibility(View.GONE);
    imageView.setVisibility(View.VISIBLE);
    imageView.setImageResource(resId);
  }

  public void setImageDrawable(Drawable drawable) {
    textView.setVisibility(View.GONE);
    imageView.setVisibility(View.VISIBLE);
    imageView.setImageDrawable(drawable);
  }
}

public class Test extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical">
  <app.test.TextImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#000"
    android:text="Click Me!"
  />
  <app.test.TextImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/icon"
  />
</LinearLayout>

Config your own layout through xml

    
package app.test;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

class TextImageButton extends FrameLayout {
  private ImageView imageView;
  private TextView textView;

  public TextImageButton(Context context) {
    this(context, null);
  }

  public TextImageButton(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public TextImageButton(Context context, AttributeSet attrs, int defaultStyle) {
    super(context, attrs, defaultStyle);
    imageView = new ImageView(context, attrs, defaultStyle);
    textView = new TextView(context, attrs, defaultStyle);
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
        LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    this.addView(imageView, params);
    this.addView(textView, params);
    setClickable(true);
    setFocusable(true);
    setBackgroundResource(android.R.drawable.btn_default);
    if (imageView.getDrawable() != null) {
      textView.setVisibility(View.GONE);
      imageView.setVisibility(View.VISIBLE);
    } else {
      textView.setVisibility(View.VISIBLE);
      imageView.setVisibility(View.GONE);
    }
  }

  public void setText(CharSequence text) {
    textView.setVisibility(View.VISIBLE);
    imageView.setVisibility(View.GONE);
    textView.setText(text);
  }

  public void setImageResource(int resId) {
    textView.setVisibility(View.GONE);
    imageView.setVisibility(View.VISIBLE);
    imageView.setImageResource(resId);
  }

  public void setImageDrawable(Drawable drawable) {
    textView.setVisibility(View.GONE);
    imageView.setVisibility(View.VISIBLE);
    imageView.setImageDrawable(drawable);
  }
}

public class Test extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical">
  <app.test.TextImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#000"
    android:text="Click Me!"
  />
  <app.test.TextImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/icon"
  />
</LinearLayout>

Provide layout for different screen size

    


package com.examples.universal;

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

public class UniversalActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- PORTRAIT/DEFAULT LAYOUT -->
<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="This is a vertical layout for PORTRAIT"
  />
  <Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Button One"
  />
  <Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Button Two"
  />
</LinearLayout>
//layout-land/main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- LANDSCAPE LAYOUT -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView  
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="The is a horizontal layout for LANDSCAPE"
  />
  <Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Button One"
  />
  <Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Button Two"
  />
</LinearLayout>
//layout-large/main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- LARGE LAYOUT -->
<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="This is the layout for TABLETS"
  />
  <Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Button One"
  />
  <Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Button Two"
  />
  <Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Button Three"
  />
  <Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Button Four"
  />
</LinearLayout>

android:layout_width and android:layout_height

    

package app.test;

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

public class Test extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
   }
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="100px"
android:layout_height="100px"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, FirstApp"
/>
</LinearLayout>