Create Button and TextView dynamically – Android sample

public class MainActivity extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            TextView textView = new TextView(this);
            textView.setText("Text View ");
            LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            layout.addView(textView, p);
 
            Button buttonView = new Button(this);
            buttonView.setText("Button");
            buttonView.setOnClickListener(mThisButtonListener);
            layout.addView(buttonView, p);
 
    }
    private OnClickListener mThisButtonListener = new OnClickListener() {
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "Hello !",
                    Toast.LENGTH_LONG).show();
        }
    };
}
This entry was posted in Android Examples Code and tagged , , , . Bookmark the permalink.


Comments are closed.



25,564 views