Button控件的点击事件

Java的代码

主要重点:

  • findViewById();
  • OnClickListener()

                  

 1 package com.example.admin.myapplication;
 2 
 3 import android.support.v7.app.AppCompatActivity;
 4 import android.os.Bundle;
 5 import android.view.View;
 6 import android.widget.Button;
 7 import android.widget.TextView;
 8 public class MainActivity extends AppCompatActivity {
 9     TextView t;
10     Button but1;
11     Button but2;
12     @Override
13     protected void onCreate(Bundle savedInstanceState) {
14         super.onCreate(savedInstanceState);
15         setContentView(R.layout.activity_main);
16         t =findViewById(R.id.t1);
17         but1=findViewById(R.id.b1);
18         but2 =findViewById(R.id.b2);
19         //通过findViewById()初始化控件
20 
21         //点击事件方法1
22         but2.setOnClickListener(new View.OnClickListener() {
23             @Override
24             public void onClick(View view) {
25                 t.setText("点击了"+ but2.getText().toString());
26             }
27         });
28     }
29     //点击事件方法2
30     public void b(View view){
31         t.setText("点击了"+ but1.getText().toString());
32     }
33 }

xml文件主要是设计手机界面(UI)

 重点:控件的运用 (Button TextView)以及属性的设置

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3 xmlns:app="http://schemas.android.com/apk/res-auto"
 4 xmlns:tools="http://schemas.android.com/tools"
 5 android:layout_width="match_parent"
 6 android:layout_height="match_parent"
 7 tools:context=".MainActivity"
 8 android:orientation="vertical"
 9     >
10 <TextView
11     android:layout_height="wrap_content"
12     android:layout_width="match_parent"
13     android:id="@+id/t1"
14     android:text="input"
15     android:textSize="25sp"
16     android:gravity="center"
17     />
18 <Button
19     android:layout_width="match_parent"
20     android:layout_height="wrap_content"
21     android:id="@+id/b1"
22     android:text="按钮1"
23     android:onClick="b"
24     />
25 <Button
26     android:layout_width="match_parent"
27     android:layout_height="wrap_content"
28     android:id="@+id/b2"
29     android:text="按钮2"
30     />
31 </LinearLayout>

app界面如图

 

转载于:https://www.cnblogs.com/xfweb/p/10544315.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值