app简单控件了解——按钮——第一种按钮点击方式——在布局中添加onClick属性(此方法已经被废弃)
如何为按钮添加监听方式总结
本文概述:
-
本文介绍了,在Android中为控件添加监听的三种常见方式
- 设置控件的onClick属性
- 采用匿名内部类
- MainActivity 实现 View.OnClickListener 接口
示例:布局代码:指定控件的onClick属性(已经被废弃掉了)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/btn_click_single" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="指定单独的点击监听器" android:textColor="#000000" android:onClick="doClick" android:textSize="15sp" /> <!-- <Button--> <!-- android:id="@+id/btn_click_public"--> <!-- android:layout_width="0dp"--> <!-- android:layout_height="wrap_content"--> <!-- android:layout_weight="1"--> <!-- android:text="指定公共的点击监听器"--> <!-- android:textColor="#000000"--> <!-- android:textSize="15sp" />--> </LinearLayout> <TextView android:id="@+id/tv_result" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingLeft="5dp" android:text="这里查看按钮的点击结果" android:textColor="#000000" android:textSize="15sp" /> </LinearLayout>
package com.example.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView tv_result; // 声明一个文本视图实例 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void doClick(View view) { tv_result = findViewById(R.id.tv_result); // 获取名叫tv_result的文本视图 tv_result.setText("您点击了此按钮_yes"); // 设置文本视图的文本内容 } }