Android应用开发学习之Toast消息提示框

作者:刘昊昱 

博客:http://blog.csdn.net/liuhaoyutz

 

本文我们来看Toast消息提示框的用法。使用Toast消息提示框一般有三个步骤:

1、  创建一个Toast对象。可以使用两种方法创建Toast对象,一种是使用Toast构造函数,另一种方法是使用Toast.makeText()方法创建。

使用构造函数创建代码如下:

Toast toast = new Toast(this);

使用Toast.makeText()方法代码如下:

Toast toast = Toast.makeText(this, “要显示的内容”, Toast.LENGTH_SHORT);

2、  调用Toast类提供的方法设置该消息提示框的对齐方式、页边距、显示的内容等等。

3、  调用Toast类的show()方法显示该消息提示框。

下面我们来看一个例子,该例子运行效果如下:

该程序的主布局文件main.xml使用默认的即可,其内容如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>


 

修改res/values/strings.xml,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Toast消息提示框应用示例:</string>
    <string name="app_name">017</string>

</resources>


主Activity文件内容如下:

package com.liuhaoyu;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //通过makeText()方法创建消息提示框
        Toast.makeText(this, "通过makeText()方法创建的消息提示框", Toast.LENGTH_LONG).show();
      	//通过构造方法创建消息提示框
     	Toast toast=new Toast(this);
      	toast.setDuration(Toast.LENGTH_SHORT);
      	toast.setGravity(Gravity.CENTER, 0, 0);	 
      	LinearLayout ll=new LinearLayout(this);	
      	ImageView iv=new ImageView(this);
      	iv.setImageResource(R.drawable.image01);
      	iv.setPadding(0, 0, 5, 0);
      	ll.addView(iv);
      	TextView tv=new TextView(this);
      	tv.setText("通过构造方法创建的消息提示框");
      	ll.addView(tv);
      	toast.setView(ll);
      	toast.show();
    }
}


原文地址:https://www.cnblogs.com/riskyer/p/3241454.html