BloggerAds

2011年10月24日 星期一

Android Toast 進階使用

 


跟之前教過的AlertDialog進階使用一樣


http://cookiesp.pixnet.net/blog/post/77342445


====================成果 如圖中的Error一樣


Toast進階  


要準備一個Toast用的layout.xml


重點用咖啡色


我下面是放在一個method 要用的時候call就好



//自製Toast==========================================================
    private void toast_error(int who,String Msg){//1是答案msg  2是錯誤msg
    LayoutInflater inflater = LayoutInflater.from(activity_calculate.this);
        View layout = inflater.inflate(R.layout.calculate_toast,null);//R.layout.calculate_toast  是自製Toast專用的layout


//下面兩個是R.layout.calculate_toast 內的元件 
        TextView msg=(TextView) layout.findViewById(R.id.textView_error);
        ImageView icon=(ImageView) layout.findViewById(R.id.imageView_toast);
        
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);

        
        if(who==1){//set answer image
        icon.setImageResource(R.drawable.answer_icon);
        msg.setText(Msg);
        }else{//set error image
        icon.setImageResource(R.drawable.error_icon);
        msg.setText("Error:"+Msg);
        }



        //Toast定位   
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 100);//0,0是正中間

        toast.show();
    }
    //自製Toast End====================================================