<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="歡迎光臨"
android:visibility="gone"/>
<Button
android:id="@+id/button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="百度一下" />
<Button
android:id="@+id/button_before"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="上一頁" />
1、匿名內部類
- /*
- * 1、初始化當前所需要的控件,如何初始化一個控件
- * findViewByid取到對應的button--返回的是一個view對象
- * findViewByid如何查找到對應view的id:gen目錄R文件下自動生成每個控件的id R.id.button1
- *
- * 2、設置Button的監聽器,通過監聽器實現我們點擊button要操作的事情
- */
2、通過接口實現,一般用於控件較多的情況,通過switch語句,使不同的按鈕響應不同方式
package com.example.hp.my;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainAc extends AppCompatActivity implements View.OnClickListener {
private TextView tv_text;
private Button button_next;
private Button button_before;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_text = (TextView) findViewById(R.id.textView);
button_next = (Button) findViewById(R.id.button_next);
button_before = (Button) findViewById(R.id.button_before);
button_before.setOnClickListener(this);
button_next.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_before:
tv_text.setText("hello");
tv_text.setVisibility(View.VISIBLE);
break;
case R.id.button_next:
Intent intent = new Intent("com.example.my.ACTION_START");
intent.addCategory("com.example.my.MY_CATEGORY");
startActivity(intent);
break;
}
}
}
3、在xml中指定方法
<Button
android:onClick="find"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="我是按鈕"
/>
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void find(View view){
Toast.makeText(this, "點擊按鈕事件", Toast.LENGTH_SHORT).show();
}
參考點擊打開鏈接