Android Button:按钮控件

按钮(Button)应该是用户交互中使用最多的组件,在很多应用程序中都很常见。当用户单击按钮的时候,会有相对应的响应动作。

下面在 WidgetDemo 工程的主界面 main.xml 中放置一个名为 Button 的按钮。文件代码如下:

 
  1. <?xml version="1.0" encoding="utf-8"?>
  2.  
  3. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:orientation="vertical">
  7.  
  8. <TextView
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. android:text="@string/hello" />
  12.  
  13. <Button
  14. android:id="@+id/button1"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:text="Button" />
  18. </LinearLayout>

其中:

 
  1. <Button
  2. android:id="@+id/button1"
  3. android:layout_width="wrap_content"
  4. android:layout_height="wrap_content"
  5. android:text="Button" />

表明在用户界面上放置了一个 ID 为“button1”的按钮,按钮的高度(layout_height)和宽度(layout_width)都会根据实际内容调整(wrap_content),按钮上显示文字为 Button,其运行效果如图 1 所示。
 

Button的应用界面
图 1  Button 的应用界面


按钮最重要的用户交互事件是“单击”事件。下面为 Button1 添加事件监听器和相应的单击事件。该过程在 WidgetDemoActivity.java 文件中完成,代码如下:

 
  1. package introduction.android.widgetdemo;
  2.  
  3. import android.support.v7.app.AppCompatActivity;
  4. import android.os.Bundle;
  5. import android.util.Log;
  6. import android.view.View;
  7. import android.widget.Button;
  8.  
  9. public class MainActivity extends AppCompatActivity {
  10.  
  11.     @Override
  12.     protected void onCreate(Bundle savedInstanceState) {
  13.         super.onCreate(savedInstanceState);
  14.         setContentView(R.layout.activity_main);
  15.         Button btn = (Button) this.findViewById(R.id.button1);
  16.         btn.setOnClickListener(new View.OnClickListener() {
  17.             @Override
  18.             public void onClick(View v) {
  19.                 //TODO Auto-generated method stub
  20.                 setTitle("button1 被用户点击了");
  21.                 Log.i("widgetDemo", "button1 被用户点击了。");
  22.  
  23.             }
  24.         });
  25.     }
  26.  
  27. }

在 WidgetDemoActivity 的 onCreate() 方法中,通过 findViewById(R.id.button1) 方法获得 Button1 的对象,通过 setOnClickListener() 方法为 Button1 设置监听器。

此处新建了一个实现 OnClickListener 接口的匿名类作为监听器,并实现了 onClick() 方法。当 Button1 被点击时,当前应用程序的标题被设置成“button1 被用户点击了”运行结果如图 2 所示。
 

点击按钮运行效果
图 2  点击按钮运行效果

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值