一个Toast例子

来源:互联网 发布:mysql 1068 42000 编辑:程序博客网 时间:2024/06/06 07:28

Java:

public class main extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        Button button1=(Button)findViewById(R.id.button1);        button1.setOnClickListener(bt1lis);        Button button2=(Button)findViewById(R.id.button2);        button2.setOnClickListener(bt2lis);    }    OnClickListener bt1lis=new OnClickListener(){@Overridepublic void onClick(View v) {showToast();}        };    OnClickListener bt2lis=new OnClickListener(){@Overridepublic void onClick(View v) {Toast.makeText(main.this,"直接输出测试", Toast.LENGTH_LONG).show();}        };    public void showToast(){    LayoutInflater li=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);    View view=li.inflate(R.layout.toast,null);    //把布局文件toast.xml转换成一个view    Toast toast=new Toast(this);    toast.setView(view);    //载入view,即显示toast.xml的内容    TextView tv=(TextView)view.findViewById(R.id.tv1);    tv.setText("Toast显示View内容");    //修改TextView里的内容    toast.setDuration(Toast.LENGTH_SHORT);    //设置显示时间,长时间Toast.LENGTH_LONG,短时间为Toast.LENGTH_SHORT,不可以自己编辑    toast.show();    }}

main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><Button android:id="@+id/button1"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Toast显示View"/><Button android:id="@+id/button2"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Toast直接输出"/></LinearLayout>

toast.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><ImageView android:src="@drawable/toast"android:layout_width="wrap_content"android:layout_height="wrap_content"/><TextView android:id="@+id/tv1"android:text=""android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout>

运行截图:


原创粉丝点击