}
package com.jj.toast_activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by jj on 2017/11/30.
*/
public class ToastUtils {
private Context Mcontext;
private Toast toast;
public ToastUtils(Context context,int layout,Student student,int gravity){
Mcontext=context;
View view = LayoutInflater.from(context).inflate(layout, null);
ImageView img= (ImageView) view.findViewById(R.id.show_iv);
TextView tv =(TextView) view.findViewById(R.id.show_tv);
img.setImageResource(student.img);
tv.setText(student.name);
toast=new Toast(context);
toast.setView(view);
toast.setGravity(gravity,0,0);
toast.setDuration(Toast.LENGTH_SHORT);
}
public void show(){
toast.show();
}
}
package com.jj.toast_activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
switch (view.getId()){
case R.id.box1:
Toast.makeText(this, "普通消息", Toast.LENGTH_SHORT).show();
break;
case R.id.box2:
Toast toast = Toast.makeText(getApplicationContext(), "居中Toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
break;
case R.id.box3:
Toast toast1 = Toast.makeText(this, "顶部Toast", Toast.LENGTH_SHORT);
toast1.setGravity(Gravity.TOP,0,0);
toast1.show();
break;
case R.id.box4:
Toast toast2 = Toast.makeText(this, "图片Toast消息", Toast.LENGTH_SHORT);
View view1 = getLayoutInflater().inflate(R.layout.mytoask, null);
toast2.setView(view1);
toast2.show();
Student student=new Student();
student.img=R.mipmap.ic_launcher;
student.name="黄盖";
ToastUtils toastUtils=new ToastUtils(this,R.layout.mytoask,student,Gravity.CENTER);
toastUtils.show();
break;
case R.id.box5:
Student student1=new Student();
student1.img=R.mipmap.ic_launcher;
student1.name="时间";
ToastUtils toastUtilss=new ToastUtils(this,R.layout.mytoask,student1,Gravity.TOP);
toastUtilss.show();
break;
}
}
}
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.jj.toast_activity.MainActivity">
android:layout_height="match_parent">
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"/>
android:layout_height="wrap_content"
android:id="@+id/show_tv"
android:text="龙门客栈"
android:textSize="20sp"
android:layout_marginLeft="13dp"/>