蜗牛—Android基础之按钮监听器

来源:互联网 发布:在淘宝店铺被限制购买 编辑:程序博客网 时间:2024/05/29 14:48

XML文件里有一个textView 和 一个按钮。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <!-- 一个id为textView的文本 宽度充满父容器 高度自适应 背景为红色 初识文字为wjj -->    <TextView        android:id="@+id/textView"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:background="#FF0000"        android:text="@string/wjj" >    </TextView>    <!-- 一个id为button的按钮  宽度自适应 高度自适应 初识文字为按钮 -->    <Button        android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="按钮" /></LinearLayout>

Java文件

package com.wjj.day_01_genesis;import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {private TextView textView;private Button button;int count = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); // 设置布局文件textView = (TextView) findViewById(R.id.textView); // 找到文本textView.setBackgroundColor(Color.BLUE); // 设置文本背景的颜色button = (Button) findViewById(R.id.button); // 找到按钮buttonOnClickLisnter lisnter = new buttonOnClickLisnter(); // 初识化一个监听器button.setOnClickListener(lisnter); // 给按钮设置监听器}class buttonOnClickLisnter implements OnClickListener { // 实现OnClickListener接口@Overridepublic void onClick(View view) { // 当绑定此监听器的按钮被按下时会调用此方法// TODO Auto-generated method stubcount++;textView.setText(count + ""); // 设置文本的显示}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}


0 0
原创粉丝点击