android对按钮的监听(基础)

来源:互联网 发布:java字符串切割 编辑:程序博客网 时间:2024/05/16 15:59


在布局文件中创建一个按钮对象

    <Button        android:id="@+id/button"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="button"/>


在java文件中创建一个监听类

    class ButtonListener implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stubcount++;textView.setText(count + "");}        }

在onCreate函数中添加监听

    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                textView = (TextView)findViewById(R.id.textView);        button = (Button)findViewById(R.id.button);                ButtonListener bl = new ButtonListener();        button.setOnClickListener(bl);    }




完整代码如下:

public class MainActivity extends Activity {private TextView textView;private Button button;int count = 0;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                textView = (TextView)findViewById(R.id.textView);        button = (Button)findViewById(R.id.button);                ButtonListener bl = new ButtonListener();        button.setOnClickListener(bl);    }        class ButtonListener implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stubcount++;textView.setText(count + "");}        }}

这样就可以对按钮实时监听,在虚拟机上点击按钮,文本栏上数字就会+1。


这就是最基本的监听代码。

0 0