A01_为Button添加监听器

本文介绍了一个简单的Android应用程序,该程序包含一个文本框用于显示数字,两个按钮分别用于增加和减少文本框中的数值。通过监听器实现加减操作,并对文本框进行居中布局,同时为界面添加了背景图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目标功能:点击“加法”按钮文本框数字加一,点击“减法按钮”,文本框数字减一。

额外功能:文本框内容居中,为布局添加背景图片。

效果:

activity_main.xml

<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:background="@drawable/tree"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="50sp"
        android:textColor="@android:color/secondary_text_light"
        android:text="0" />
    <Button 
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="加法"
        />
    <Button 
        android:id="@+id/subButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="减法"
        />
</LinearLayout>

MainActivity.java

package com.haut.listener;

import android.os.Bundle;
import android.app.Activity;
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 Button button;
	private Button subButton;
	private TextView textView;
	// 文本框中的内容
	private int count = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 获取加法按钮
		button = (Button) findViewById(R.id.button);
		// 获取减法按钮
		subButton = (Button) findViewById(R.id.subButton);
		// 获取文本框
		textView = (TextView) findViewById(R.id.textView);
		// 设置文本字体大小
		textView.setTextSize(50);
		// 创建加法监听器
		ButtonListener buttonListener = new ButtonListener();
		// 添加监听器
		button.setOnClickListener(buttonListener);
		// 添加并设置减法监听器
		subButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				count--;
				textView.setText(count + "");
			}
		});
	}

	// 菜单
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	// 加法监听器
	public class ButtonListener implements OnClickListener {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			count++;
			textView.setText(count + "");
		}

	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值