在android 中利用button 按钮设置监听事件
16lz
2021-01-25
新建一个空工程,然后当你点击button 按钮时,会提示你
<span style="color:#ff0000;">"TextView里的文字发生了改变,你注意到了吗?", </span>
在android 中利用button 按钮设置监听事件
package com.example.androidtest;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.widget.Button;import android.widget.Toast;import android.view.View;import android.widget.TextView; import android.view.View.OnClickListener;public class MainActivity extends Activity {private TextView textview1; private Button button1; @Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); textview1 = (TextView)findViewById(R.id.textView1); button1 = (Button)findViewById(R.id.button1); button1=(Button)findViewById(R.id.button1); //增加事件响应 button1.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { //Toast提示控件 Toast.makeText(MainActivity.this, "TextView里的文字发生了改变,你注意到了吗?", Toast.LENGTH_LONG).show(); //将TextView的文字发生改变 textview1.setText("欢迎你 前辈"); // textview1.setText("你好,前辈"); } }); }@Overridepublic 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;}}
XML中的配置文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" 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" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_marginTop="87dp" android:layout_toRightOf="@+id/textView1" android:text="Button test" /> </RelativeLayout>
更多相关文章
- android textview改变部分文字的颜色和string.xml中文字的替换
- 【Android(安卓)开发教程】使用Intent-Filter
- Android(安卓)自定义EditText输入框 带清空按钮
- 【Android(安卓)开发教程】解决Intent-Filter的冲突
- android 显示单选列表对话框 builder.setSingleChoiceItems
- Activity四种启动模式
- Android之FloatingActionButton使用
- Android(安卓)测量文字宽高
- 安卓应用的界面编程(2)