1.XML按钮定义
显示:
2.后台代码创建控件并注册事件
import android.annotation.SuppressLint;import android.app.Activity;import android.app.ActionBar.LayoutParams;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.LinearLayout;/** * 简单动态产生按钮,并绑定事件 * * @author zhongyang * */public class Button_Two extends Activity { private LinearLayout parentLayout = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 指定布局面板 createParentLayout(); // 创建按钮 CreateButton(); } // 产生布局面板 @SuppressLint("NewApi") private void createParentLayout() { parentLayout = new LinearLayout(this); LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); parentLayout.setLayoutParams(layoutParams); setContentView(parentLayout); } // 添加按钮并注册事件 @SuppressLint("NewApi") private void CreateButton() { Button btnOne = new Button(this); btnOne.setText("显示其他Activity"); btnOne.setOnClickListener(new btnOneListener()); LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); btnOne.setLayoutParams(layoutParams); parentLayout.addView(btnOne); } // 按钮点击事件方法 class btnOneListener implements View.OnClickListener { public void onClick(View v) { Button thisBtn = (Button) v; thisBtn.setWidth(100); thisBtn.setText("按钮点击事件触发了"); } }}
显示:
3.XML创建控件 注册click事件
import android.app.Activity;import android.content.res.ColorStateList;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;/** * 访问布局视图中的按钮并注册事件 * @author zhongyang * */public class ButtonThree extends Activity { private TextView txtOne = null; private Button btnOne = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 设置布局视图,初始化控件 setContentView(R.layout.button_three); txtOne = (TextView) this.findViewById(R.id.txtOne); btnOne = (Button) this.findViewById(R.id.btnOne); } // 按钮点击事件 public void btnOneClick(View view) { Button btn = (Button) view; btn.setTextSize(25); // 修改TextView的值 txtOne.setText("按钮One触发点击事件"); }}
显示: