andriod 动态创建控件
作者:互联网
andriod 动态创建控件
Button btNext=(Button)findViewById(R.id.next); btNext.setOnClickListener(new Button.OnClickListener(){ public void onClick(View view){ //创建一个布局管理器控件 LinearLayout linearLayout=new LinearLayout(MainActivity.this); setContentView(linearLayout); //设置orientation为horizontal,1表示为vertical linearLayout.setOrientation(0); TextView tvSecond=new TextView(MainActivity.this); tvSecond.setText("这是Android奉献给你的第二个页面"); Button btNext2=new Button(MainActivity.this); btNext2.setText("下一步"); btNext2.setId(2); LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); linearLayout.addView(tvSecond,lp1); linearLayout.addView(btNext2,lp1); btNext2.setOnClickListener(new View.OnClickListener(){ public void onClick(View view){ //这次只放置一个TextView不需要布局管理器 TextView tv3=new TextView(MainActivity.this); tv3.setText("恭喜你已来到最后一个页面!"); //直接让页面显示一个TextView setContentView(tv3); } }); } });
类似 Button btNext=(Button)findViewById(R.id.next); btNext.setOnClickListener(new ButtonCreateClickListener()); } private class ButtonCreateClickListener implements View.OnClickListener { public void onClick(View view) { //创建一个布局管理器控件 LinearLayout linearLayout = new LinearLayout(MainActivity.this); setContentView(linearLayout); //设置orientation为horizontal,1表示为vertical linearLayout.setOrientation(0); TextView tvSecond = new TextView(MainActivity.this); tvSecond.setText("这是Android奉献给你的第二个页面"); Button btNext2 = new Button(MainActivity.this); btNext2.setText("下一步"); btNext2.setId(2); LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); linearLayout.addView(tvSecond, lp1); linearLayout.addView(btNext2, lp1); btNext2.setOnClickListener(new btNext2ClickListener()); } } private class btNext2ClickListener implements View.OnClickListener { public void onClick(View v) { //这次只放置一个TextView不需要布局管理器 TextView tv3 = new TextView(MainActivity.this); tv3.setText("恭喜你已来到最后一个页面!"); //直接让页面显示一个TextView setContentView(tv3); } }
创建按钮
Button btNext=(Button)findViewById(R.id.next); btNext.setOnClickListener(new ButtonCreateClickListener()); } private class ButtonCreateClickListener implements View.OnClickListener { public void onClick(View view) { //创建一个button按钮 Button btn1 = new Button( MainActivity.this); btn1.setText("this is a button"); btn1.setId(1); TableLayout pTableLayout=(TableLayout)findViewById(R.id.table2); pTableLayout.addView(btn1); } }
可以是
private class ButtonCreateClickListener implements View.OnClickListener { public void onClick(View view) { //创建一个button按钮 Button btn1 = new Button( MainActivity.this); btn1.setText("this is a button"); btn1.setId(1); TableRow pTableRow=(TableRow)findViewById(R.id.TableRow2); pTableRow.addView(btn1); } }
标签:控件,Button,动态创建,MainActivity,btNext2,andriod,new,TextView,View 来源: https://blog.51cto.com/u_12139363/3027227