android中toast的应用:
本程序实现了用户点击按钮,桌面显示用户在程序中设定好的提示信息
package com.dou.button.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity
{
private Button btn1 = null;
private Button btn2 = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//确定按钮的操作代码
btn1 = (Button)findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(MainActivity.this, "你点击了确定按钮",Toast.LENGTH_LONG ).show();
}
});
//推出按钮的操作代码
btn2 = (Button)findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(MainActivity.this, "你点击了退出按钮", Toast.LENGTH_LONG).show();
}
});
}
}
注:当有多个按钮时以上代码会显得冗余,可以进行修改,修改完成后的代码为以下
package com.dou.button.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity
{
private Button btn1 = null;
private Button btn2 = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//确定按钮的操作代码
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn1.setOnClickListener(listener);
btn2.setOnClickListener(listener);
}
private OnClickListener listener = new OnClickListener()
{
public void onClick(View v)
{
Button btn = (Button)v;
switch(btn.getId())
{
case R.id.btn1:
Toast.makeText(MainActivity.this, "你点击了确定按钮", Toast.LENGTH_LONG).show();
break;
case R.id.btn2:
Toast.makeText(MainActivity.this, "你点击了退出按钮", Toast.LENGTH_LONG).show();
break;
}
}
};
}