Joyson
Joyson

Reputation: 1653

programmatically position a EditText component in android?

how do i position an edit text dynamically at runtime in android?

followig is my code:

public class ABCActivity extends Activity   {
  EditText ed;

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

    ed = new EditText(ABCActivity.this);
    ed.setEnabled(false);    
    layout =new LinearLayout(this);  
    LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT, 1.0f);            
    layout.setLayoutParams(params);
    btn = new Button(this); 
    btn.setLayoutParams(params);
    btn.setText("Change");

    RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) ed.getLayoutParams();
    params2.leftMargin = 10;
    params2.topMargin = 10;
    ed.setLayoutParams(params2);

    layout.addView(btn);   
    layout.addView(ed);

   }    
}

Gives Force close at :

RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) ed.getLayoutParams();

error: Null pointer Exception i tried using relative layout ..... but does not work

Upvotes: 2

Views: 6735

Answers (2)

Aqif Hamid
Aqif Hamid

Reputation: 3521

Your can set position of your EditText this way, I have give it dummy values of 10, 10.

         RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ed.getLayoutParams();
         params.leftMargin = 10;
         params.topMargin = 10;
         ed.setLayoutParams(params);

Upvotes: 1

Raghav Sood
Raghav Sood

Reputation: 82533

There is a great tutorial on this by Lars Vogel here. Basically you have to use the LayoutParams specific to your layout to position views through Java.

Upvotes: 1

Related Questions