目标功能:点击“加法”按钮文本框数字加一,点击“减法按钮”,文本框数字减一。
额外功能:文本框内容居中,为布局添加背景图片。
效果:
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 + "");
}
}
}