Toast 显示文本,图片,及图文

<RelativeLayout 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"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="toastText"
        android:text="Toast显示文本" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:onClick="toastImage"
        android:text="Toast显示图片" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button2"
        android:onClick="toastTextAndImage"
        android:text="Toast显示文本和图片" />


</RelativeLayout>
<pre name="code" class="java">package com.ashzheng.testcodingke;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
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);
    }

    public void toastText(View v) {
        Toast.makeText(this, "Hellow", Toast.LENGTH_SHORT).show();
    }

    public void toastImage(View v) {
        Toast t = new Toast(this);
        ImageView iv = new ImageView(this);
        iv.setImageResource(R.mipmap.puzzle_1);
        t.setView(iv);
        t.setDuration(Toast.LENGTH_LONG);
        t.setGravity(Gravity.CENTER_VERTICAL|Gravity.LEFT, 0, 0);
        t.show();
    }
    public void toastTextAndImage(View v){
        Toast t = new Toast(this);

        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.mipmap.puzzle_1);

        TextView textView = new TextView(this);
        textView.setText("显示图文");

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(imageView);
        linearLayout.addView(textView);

        t.setView(linearLayout);
        t.setDuration(Toast.LENGTH_SHORT);
        t.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT, 0, 0);
        t.show();
    }

}


 
 

你可能感兴趣的:(android)