<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="简单提示" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="带图片提示" /> </LinearLayout>
package com.example.toast; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button simple=(Button) findViewById(R.id.button1); simple.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { Toast toast=Toast.makeText(MainActivity.this,"简单的提示信息", Toast.LENGTH_SHORT); toast.show(); } }); Button bn=(Button) findViewById(R.id.button2); bn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { Toast toast=new Toast(MainActivity.this); toast.setGravity(Gravity.CENTER, 0,0 ); ImageView image=new ImageView(MainActivity.this); image.setImageResource(R.drawable.nongyu); LinearLayout ll=new LinearLayout(MainActivity.this); ll.addView(image); TextView textView=new TextView(MainActivity.this); textView.setTextSize(30); textView.setTextColor(Color.MAGENTA); textView.setText("带图片的提示信息"); ll.addView(textView); toast.setView(ll); toast.setDuration(Toast.LENGTH_LONG); toast.show(); } }); } }
代码中使用了两种方法,一个是直接用toast.makeText创建,还一个是用new Toast创建带图片的toast.
时间: 2024-10-10 15:12:17