</LinearLayout>
--------------------------Activity代码------------------------
public class ToastActivity extends Activity implements OnClickListener {
private Button style1btn;
private Button style2btn;
private Button style3btn;
private Button style4btn;
private Toast toast = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_main);
initViews();
initListeners();
}
private void initViews() {
style1btn = (Button) findViewById(R.id.style1_btn);
style2btn = (Button) findViewById(R.id.style2_btn);
style3btn = (Button) findViewById(R.id.style3_btn);
style4btn = (Button) findViewById(R.id.style4_btn);
}
private void initListeners() {
style1btn.setOnClickListener(this);
style2btn.setOnClickListener(this);
style3btn.setOnClickListener(this);
style4btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
AlertDialog.Builder builder;
AlertDialog dialog;
switch (v.getId()) {
case R.id.style1_btn:
Toast.makeText(ToastActivity.this, "系统默认的Toast样式", Toast.LENGTH_LONG).show();
break;
case R.id.style2_btn:
toast = Toast.makeText(ToastActivity.this, "改变Toast显示位置的样式", Toast.LENGTH_LONG);
/**设置显示位置为居中*/
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
break;
case R.id.style3_btn:
toast = Toast.makeText(ToastActivity.this, "自定义带图片的Toast样式", Toast.LENGTH_LONG);
LayoutInflater inflater = getLayoutInflater();
/**自定义布局*/
View view = inflater.inflate(R.layout.my_custom_toast, (ViewGroup) findViewById(R.id.toast_layout));
toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(view);
toast.show();
break;
case R.id.style4_btn:
LayoutInflater inflater1 = getLayoutInflater();
View styleView = inflater1.inflate(R.layout.my_custom_toast, (ViewGroup) findViewById(R.id.toast_layout));
TextView tv = (TextView) styleView.findViewById(R.id.txt_context);
tv.setText("长时间显示的Toast就是自己定义的一个Dialog!");
builder = new AlertDialog.Builder(this);
builder.setView(styleView);
dialog = builder.create();
dialog.show();
break;
default:
break;
}
}
}
原文地址:http://blog.csdn.net/true100/article/details/45093303