Sunday, June 19, 2011

Add view using Java code

It's a example to add view in run-time using Java code, instead of XML.

Add view using Java code

A empty LinearLayout with id mainlayout is defined. in the layout, main.xml. Additional view can be added using addView(view) method of LinearLayout.

<?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"
    >
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/mainlayout"
    />
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>


package com.exercise.AndroidAddView;

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

public class AndroidAddViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainlayout);
        
        //Add view using Java Code
        ImageView imageView = new ImageView(AndroidAddViewActivity.this);
  imageView.setImageResource(R.drawable.icon);
  LayoutParams imageViewLayoutParams 
   = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  imageView.setLayoutParams(imageViewLayoutParams);
  
  mainLayout.addView(imageView);
        
    }
}


Related:
- Programmatically create layout and view, with ID assigned by setId().


No comments: