- Instantiate the linear layout:
LinearLayout layout =
findViewById(R.id.linear_layout);
- Instantiate the textview and button. Declare them as final
(constant) so that they
can be used in the inner class of the event handler:
final TextView txtWord = new TextView(this);
final Button btnNextWord = new Button(this);
- Set the text in the widgets:
txtWord.setText(words[wordIndex++]);
btnNextWord.setText("NEXT WORD");
- Set the textSize attribute for the widgets:
txtWord.setTextSize(
TypedValue.COMPLEX_UNIT_SP, 24);
btnNextWord.setTextSize(
TypedValue.COMPLEX_UNIT_SP, 24);
- Let the layout parameters for the widgets:
LinearLayout.LayoutParams params =
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(50, 50, 0, 0);
txtWord.setLayoutParams(params);
btnNextWord.setLayoutParams(params);
- Place the widgets in the linear layout:
layout.addView(txtWord);
layout.addView(btnNextWord);
- Add an onClick listener to the button:
// Add onClick listener to button.
btnNextWord.setOnClickListener(
new View.OnClickListener( ) {
@Override
public void onClick(View view) {
txtWord.setText(
words[(wordIndex++ % numWords)]);
}
});