Android Toast的基本使用
一、 说明
本文主要讲一下Android Toast的基本使用。
二、 所用工具
Android Studio
三、 具体内容
Toast:
主要用来提示信息
语法:
Toast.makeText(当前上下文, “要提示的内容”, 显示的时长).show()
例子:
Xml代码:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="@+id/btn_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="显示"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
界面效果图:
Activity代码:
public class MainActivity extends AppCompatActivity {
Activity mActivityContext;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActivityContext=this;
Button btnSubmit = findViewById(R.id.btn_show);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
midToast("显示内容",Toast.LENGTH_LONG);
}
});
}
//我这里为了方便提取出来写了一个方法
public void midToast(String str,int showTime)
{
Toast toast = Toast.makeText(mActivityContext, str, showTime);
//设置Toast显示的位置
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,100,100);
//获取组件
TextView v = toast.getView().findViewById(android.R.id.message);
//设置Toast的字体颜色
v.setTextColor(Color.BLACK);
toast.show();
}
}
点击按钮后的效果图: