今天观看视频学习了Toast的基本用法,弹出框,弹框位置的变化,弹框加上icon,以及弹框点击次数和弹框的秒数的设置;
新建一个activity,在Main里面设置一个按钮,然后跳转,然后再Toastactivity里面设置几个按钮,然后再前面代码里面声明一下,
package com.example.yangy.myapplication123; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.yangy.myapplication123.util.Toastutil; public class ToastActivity extends ActionBarActivity { private Button mToast1,mToast2,mToast3,mToast4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_toast); mToast1= (Button) findViewById(R.id.toast_1); mToast2= (Button) findViewById(R.id.toast_2); mToast3= (Button) findViewById(R.id.toast_3); mToast4= (Button) findViewById(R.id.toast_4); OnClick onClick=new OnClick(); mToast1.setOnClickListener(onClick); mToast2.setOnClickListener(onClick); mToast3.setOnClickListener(onClick); mToast4.setOnClickListener(onClick); } class OnClick implements View.OnClickListener{ public void onClick(View v) { switch (v.getId()){ case R.id.toast_1: Toast.makeText(ToastActivity.this,"Toast写入文字",Toast.LENGTH_LONG).show(); break; case R.id.toast_2: Toast toastcenter=Toast.makeText(getApplicationContext(),"居中Toast",Toast.LENGTH_LONG); toastcenter.setGravity(Gravity.CENTER,0,0);//居中显示Toast toastcenter.show(); break; case R.id.toast_3: Toast toastCustom=new Toast(getApplicationContext()); LayoutInflater inflater=LayoutInflater.from(ToastActivity.this); View view= inflater.inflate(R.layout.layout_toast, null); ImageView imageView= (ImageView) view.findViewById(R.id.iv_toast); TextView textView= (TextView) view.findViewById(R.id.tv_toast); imageView.setImageResource(R.drawable.icon_address); textView.setText("自定义文字Toast"); toastCustom.setView(view); toastCustom.show(); break; case R.id.toast_4: Toastutil.showMsg(getApplicationContext(),"包装过的toast");//只显示最后点的秒数 break; } } } }
Toastactivity
其中要是设置弹框点击次数和弹框的秒数,需要自己另外设置一个包util里面自己包装一个类;
package com.example.yangy.myapplication123.util; import android.content.Context; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.widget.Toast; import com.example.yangy.myapplication123.R; public class Toastutil { public static Toast mToast; public static void showMsg(Context context,String msg){ if(mToast==null) { mToast=Toast.makeText(context,msg,Toast.LENGTH_LONG); }else { mToast.setText(msg); } mToast.show(); } }
解决了昨天的问题,用之前废除的函数编写代码也是可以的,一步一步学,不能越界学习;
自己敲写完成代码后,自己运行然后发现自己的错误,前面一章 的内容需要自己导入依赖,然而我不会导入依赖,总会出现各种问题,明天着重学习怎么样将依赖导入自己的AS中;
原文地址:https://www.cnblogs.com/1234yyf/p/12287714.html
时间: 2024-10-03 23:00:09