在 Android Studio 开发环境中实现一个按钮的例子,通过按钮改变文本的内容。
1. 添加一个按钮
新建一个 Blank Project 之后, 在 activity_main.xml:

中添加一个按钮, 可以使用design
模式来添加,:

添加之后的xml文件中按钮的一部分(不完整)大概是这个样子的, 当然这里改了id和text:
1 2 3 4 5 6 7 8 9 10 11
| <Button android:text="Button-change" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="74dp" android:id="@+id/button_1" android:layout_below="@+id/textView" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginLeft="85dp" android:layout_marginStart="85dp" />
|
此时的textView是这样的:
1 2 3 4 5 6 7 8
| <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="activity_main 的 xml" android:id="@+id/textView" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" />
|
2. 对按钮添加 onClick
在 activity_main.xml 中, 这个按钮的xml 中添加android:onClick="btn1_click"
, 引号里面的内容可以自己定义.
非常重要,别忘了这一步!!!
3. onClick 事件设置
在 MainActivity.java 中 首先import:import android.widget.*;
, 然后创建一个button对象, 还有textView, 即上面那个文本框 :
1 2 3 4
| Button button ; TextView textView ; int flag = 1;
|
然后在 onCreate() 方法中给button指定id, 别忘了 textView, onCreate方法是这样的:
1 2 3 4 5 6 7
| @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button_1); textView = (TextView) findViewById(R.id.textView); }
|
然后是点击按钮之后的动作, 为什么是btn1_click呢?, 因为上面的android:onClick="btn1_click"
:
1 2 3 4 5 6 7 8 9 10 11 12
| public void btn1_click(View view) { if (flag) { String str_1 = "botton clicked"; textView.setText(str_1); flag = 0; } else{ String str_2 = "activity_main 的 xml"; textView.setText(str_2); flag = 1; } }
|
搞定!
屏幕录制