Android的相关事件

时间:2023-09-08 10:55:56

Android的相关事件

1.Toast信息提醒

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast; public class FirstActivity extends AppCompatActivity {
private static final String TAG = "FirstActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
// 获取按钮
Button button1 = (Button) findViewById(R.id.button_1);
//点击事件
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// 弹出信息
Toast.makeText(FirstActivity.this,"You click button1",
Toast.LENGTH_SHORT).show();
}
});
}
}

2.在活动中使用Menu

res下新建一个Director,名为menu,在menu中建一个main的menuresourceFile(右键新建即可)

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/add_item"
android:title="Add" />
<item
android:id="@+id/remove_item"
android:title="Remove" />
</menu>

FirstActivity.java

package com.example.activitytest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast; public class FirstActivity extends AppCompatActivity { private static final String TAG = "FirstActivity"; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
//获取按钮
Button button1 = (Button) findViewById(R.id.button_1);
//点击事件
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//弹出信息
Toast.makeText(FirstActivity.this, "You click button1",
Toast.LENGTH_SHORT).show();
}
});
} //定义菜单的选项
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
} //定义菜单选项的点击事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_item:
Toast.makeText(this, "点击了add", Toast.LENGTH_LONG).show();
break;
case R.id.remove_item:
Toast.makeText(this, "点击了remove", Toast.LENGTH_LONG).show();
break;
default:
}
return true;
}
}

3.销毁一个活动

一般我们点击Back按钮可以实现返回的效果,如果需要自定义销毁可以调用finish()方法

 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
//获取按钮
Button button1 = (Button) findViewById(R.id.button_1);
//点击事件
button1.setOnClickListener(new View.OnClickListener() {
@Override
//销毁一个活动
public void onClick(View v) {
//销毁 和Back键的效果是一样的
finish();
}
});
}