Android默認(rèn)Toast非常簡(jiǎn)潔和易于使用,但有時(shí)我們的程序使用默認(rèn)Toast時(shí),它與程序的總體樣式不匹配,今天是武林技術(shù)頻道小編為你搜集的android之Toast的使用方法,一起來了解一下吧!
android之Toast的使用方法
android:id="@+id/toast_layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:background="#DAAA"
>
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
在這個(gè)地方要注意,我們給LinearLayout添加的id屬性,在后面的代碼中我們需要使用到。在程序中,我們可以通過如下代碼創(chuàng)建我們自己的Toast:
?
?
public class MainActivity extends Activity
{
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//獲取LayoutInflater對(duì)象,該對(duì)象能把XML文件轉(zhuǎn)換為與之一直的View對(duì)象
LayoutInflater inflater = getLayoutInflater();
//根據(jù)指定的布局文件創(chuàng)建一個(gè)具有層級(jí)關(guān)系的View對(duì)象
//第二個(gè)參數(shù)為View對(duì)象的根節(jié)點(diǎn),即LinearLayout的ID
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
//查找ImageView控件
//注意是在layout中查找
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.head);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("自定義Toast演示程序");
Toast toast = new Toast(getApplicationContext());
//設(shè)置Toast的位置
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
//讓Toast顯示為我們自定義的樣子
toast.setView(layout);
toast.show();
}
});
}
}
運(yùn)行效果:
?
上文是關(guān)于android之Toast的使用方法,相信大家都有了一定的了解,想要了解更多的技術(shù)信息,請(qǐng)繼續(xù)關(guān)注武林技術(shù)頻道吧!