TIP

There are times when you need to add views programmatically in Android, i.e without specifying the views in the layout xml file.

The way to do it is very simple... Here, i've shown how to add the textview programmatically...

 package com.example.tut.tut_10_3;

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

public class MainActivity extends Activity {

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

LinearLayout.LayoutParams linpar =
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT );


LinearLayout linlay = new LinearLayout(this);
linlay.setOrientation(LinearLayout.VERTICAL);


LayoutParams viewpar =
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);


TextView tv = new TextView(this);
tv.setText("Textview");
tv.setLayoutParams(viewpar);
linlay.addView(tv);


this.addContentView(linlay, linpar);
}
}
  






Leave a Comment  
Download Code(69)





All rights reserved, the content is copyrighted to the author.

RELATED POST