之前跟大家说到了dialog的一些使用,这次讲讲Toast的使用
总体来讲有4种使用方式:
1.默认的Toast 2.自定义的Toast 3.带有图片的Toast 4.完全自定义view的Toast
源码
- public class MainActivity extends Activity implements View.OnClickListener{
- private Button btn1;
- private Button btn2;
- private Button btn3;
- private Button btn4;
- @Override
- protected void onCreate(@Nullable Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- btn1 = (Button) findViewById(R.id.btn1);
- btn2 = (Button) findViewById(R.id.btn2);
- btn3 = (Button) findViewById(R.id.btn3);
- btn4 = (Button) findViewById(R.id.btn4);
- btn1.setOnClickListener(this);
- btn2.setOnClickListener(this);
- btn3.setOnClickListener(this);
- btn4.setOnClickListener(this);
- }
- @Override
- public void onClick(View view) {
- switch (view.getId()){
- case R.id.btn1:
- Toast toast1 = Toast.makeText(this,"默认的Toast",Toast.LENGTH_SHORT);
- toast1.show();
- break;
- case R.id.btn2:
- Toast toast2 = Toast.makeText(this, "自定义位置的Toast", Toast.LENGTH_SHORT);
- toast2.setGravity(Gravity.CENTER,0,0); //通过此方法设置Toast的位置
- toast2.show();
- break;
- case R.id.btn3:
- Toast toast3 = Toast.makeText(this,"带有图片的Toast", Toast.LENGTH_SHORT);
- ImageView iv = new ImageView(this);
- iv.setImageResource(R.mipmap.ic_launcher);
- LinearLayout ll = (LinearLayout) toast3.getView(); //此处可能习惯使用setXXX,但是实际操作发现是通过getView方法
- ll.addView(iv); //获得Toast中的view
- toast3.show();
- break;
- case R.id.btn4:
- Toast toast4 = new Toast(this);
- toast4.setGravity(Gravity.CENTER,0,0);
- toast4.setView(getLayoutInflater().inflate(R.layout.toast,null)); //通过setView方法完全设置自定义的View
- toast4.show();
- break;
- }
- }
- }
自定义的view:
测试的时候想了下,Toast虽然是继承Object的,与view没什么关系,可是细想toast也很像一个view来表现数据,也可换种思维理解,toast看作一个view的话,默认自身就带有布局,通过getView 方法获取对象,可以设置相应的参数, 提供set View方法让我们完全自定义自己的view
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="match_parent"
- android:layout_height="match_parent">
- <TextView
- android:text="自定义的Toast"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- <LinearLayout
- android:gravity="center_vertical"
- android:orientation="horizontal"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- <ImageView
- android:src="@mipmap/ic_launcher"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- <TextView
- android:text="自定义view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </LinearLayout>
- </LinearLayout>
以上也只是个人看法,仅供参考 。