布局文件内容:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorGray"
android:orientation="vertical"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/imageToast"
android:onClick="imageToast"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="normalToast"
android:text="@string/normalToast"
/>
</RelativeLayout>
主程序的内容:
package com.toby.personal.testlistview;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
final private static String TAG = "Toby_Test";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void imageToast(View view) {
Toast toast = new Toast(this);
toast.setGravity(Gravity.CENTER, 0, 0); // toast 显示位置
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_launcher);
imageView.setLayoutParams(new ViewGroup.LayoutParams(80, 80));
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayout ll = new LinearLayout(this);
ll.addView(imageView);
TextView textView = new TextView(this);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
textView.setTextColor(Color.MAGENTA);
textView.setText(R.string.imageToast);
ll.addView(textView);
toast.setView(ll);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
}
public void normalToast(View view) {
Toast.makeText(this, R.string.normalToast, Toast.LENGTH_SHORT).show();
}
}
示例程序运行效果:
参考文献:《疯狂Android讲义(第2版)》