public class MainActivity extends AppCompatActivity {
Button btn;
TextView tv;
private OnClickListener btnListener = new OnClickListener() {
@Override
public void onClick(View view) {
tv.setText("helloworld!");
btn.setText("helloworld!");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
btn = new Button(this);
btn.setText("this is a button");
btn.setLayoutParams(params);
tv = new TextView(this);
tv.setText("this is a textview");
tv.setLayoutParams(params);
layout.addView(tv);
layout.addView(btn);
LinearLayout.LayoutParams layoutparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
this.addContentView(layout,layoutparams);
btn.setOnClickListener(btnListener);
}
}
运行效果
点击Button效果如下