Button控件的點擊事件

 2023-12-06 阅读 16 评论 0

摘要: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

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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/190659.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息