一个Toast例子

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(){

		@Override
		public void onClick(View v) {
			showToast();
		}
    	
    };
    OnClickListener bt2lis=new OnClickListener(){
		@Override
		public 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>

运行截图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值