android中toast的應用:html
本程序實現了用戶點擊按鈕,桌面顯示用戶在程序中設定好的提示信息android
package com.dou.button.activity;app
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;ide
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();
}
});
}
}this
注:當有多個按鈕時以上代碼會顯得冗餘,能夠進行修改,修改完成後的代碼爲如下spa
package com.dou.button.activity;htm
import android.app.Activity;blog
import android.os.Bundle;ci
import android.view.View;get
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;
}
}
};
}