Saturday, June 16, 2012

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

This example demonstrate how to create layout and view at run time using Java code, instead of XML code. We can assign IDs for the layouts/views by calling setId() mdthod.

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

In order to call setId() with named id, create /res/values/ids.xml to define out ID resources.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item type="id" name="layout_id"/>
    <item type="id" name="image_id" />
</resources>


Main code.
package com.exercise.AndroidSetId;

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

public class AndroidSetIdActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        LinearLayout layout = new LinearLayout(AndroidSetIdActivity.this);
        layout.setId(R.id.layout_id);
        LayoutParams layoutParams 
         = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        layout.setLayoutParams(layoutParams);
        layout.setOrientation(LinearLayout.VERTICAL);
        
        ImageView imageView = new ImageView(AndroidSetIdActivity.this);
        imageView.setId(R.id.image_id);
        imageView.setImageResource(R.drawable.ic_launcher);
        LayoutParams imageViewLayoutParams 
         = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        imageView.setLayoutParams(imageViewLayoutParams);
        
        layout.addView(imageView);
        
        setContentView(layout);
        
        layout.setOnClickListener(viewOnClickListener);
        imageView.setOnClickListener(viewOnClickListener);
    }
    
    OnClickListener viewOnClickListener
    = new OnClickListener(){

  @Override
  public void onClick(View v) {
   
   int myId = v.getId();
   
   Toast.makeText(AndroidSetIdActivity.this, 
     "ID: " + String.valueOf(myId) + " clicked", 
     Toast.LENGTH_LONG).show();
  }};
}



3 comments:

Unknown said...

good

Unknown said...

good example,

i have a issues in layout click event in not get id

Mallikarjun said...

good, but what if we have big list, and if i want to add id's for each item. is there a better solution than adding ids in resources?