目标效果:
在这个程序中,将实现两个按钮:普通按钮和图片按钮,当用户点击不同的按钮时,在其下方的文本框中显示点击的次数。
布局实现:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
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"
android:background="@drawable/bg5">
<Button
android:id="@+id/normalButton"
android:text="普通按钮"
android:textSize="16pt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageButton
android:id="@+id/imageButton"
android:layout_width="158dp"
android:layout_height="wrap_content"
android:contentDescription="图片按钮"
android:src="@drawable/imagebutton" />
<View
android:layout_marginTop="20dp"
android:layout_width="270dp"
android:layout_height="2dip"
android:background="#FF909090"/>
<TextView
android:id="@+id/showClickNormal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="您没有单击普通按钮"
android:textSize="20dp"/>
<TextView
android:id="@+id/showClickImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="您没有单击图片按钮"
android:textSize="20dp"/>
</LinearLayout>
事件响应:
package com.example.buttondemo;
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.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
Button b1;
ImageButton b2;
TextView show1;
TextView show2;
int count1=0;
int count2=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.normalButton);
show1=(TextView) findViewById(R.id.showClickNormal);
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
count1++;
show1.setText("您一共单击了"+count1+"次普通按钮");
}
});
b2=(ImageButton) findViewById(R.id.imageButton);
show2=(TextView) findViewById(R.id.showClickImage);
b2.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
count2++;
show2.setText("您一共单击了"+count2+"次普通按钮");
}
});
}
@Override
public 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;
}
}