2011-07-14 28 views
46

我显示敬酒消息的结果的颜色,如果使用下面的代码声明:安卓:如何设置敬酒的文本

Toast.makeText(getBaseContext(), "Please Enter Price", Toast.LENGTH_SHORT).show(); 

它显示为白色的文字在白色背景上,因此它不能被阅读!我的问题是,我怎样才能改变吐司文字的颜色?

+0

我希望[这](http://linkflows.blogspot.in/2014/08/creating-custom-toast-using-xml.html)将帮助你。 (http://linkflows.blogspot.in/2014/08/creating-custom-toast-using-xml.html) – 2014-08-06 10:46:13

回答

15

您可能希望创建一个自定义吐司

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      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" 
      > 
<ImageView android:id="@+id/image" 
      android:layout_width="wrap_content" 
      android:layout_height="fill_parent" 
      android:layout_marginRight="10dp" 
      /> 
<TextView android:id="@+id/text" 
      android:layout_width="wrap_content" 
      android:layout_height="fill_parent" 
      android:textColor="#FFF" 
      /> 
</LinearLayout> 

-

LayoutInflater inflater = getLayoutInflater(); 
View layout = inflater.inflate(R.layout.toast_layout, 
          (ViewGroup) findViewById(R.id.toast_layout_root)); 

ImageView image = (ImageView) layout.findViewById(R.id.image); 
image.setImageResource(R.drawable.android); 
TextView text = (TextView) layout.findViewById(R.id.text); 
text.setText("Hello! This is a custom toast!"); 

Toast toast = new Toast(getApplicationContext()); 
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); 
toast.setDuration(Toast.LENGTH_LONG); 
toast.setView(layout); 
toast.show(); 

Source

+0

非常感谢你 –

114

你可以做到这一点非常很容易,无需通过修改默认Toast创建自定义布局:

Toast toast = Toast.makeText(this, resId, Toast.LENGTH_SHORT); 
TextView v = (TextView) toast.getView().findViewById(android.R.id.message); 
v.setTextColor(Color.RED); 
toast.show(); 

,你可以找到在Android SDK中使用的默认视图敬酒布局:

$ Android的SDK $ /平台/ Android的8 /数据/ RES /布局/ transient_notification.xml

+56

你也可以'toast.getView() .setBackgroundColor(Color.RED);'设置整个Toast区域的背景颜色。 – Chris

+0

^- 虽然我的电话在默认灰色背景之后添加了背景。 –

5

您也可以使用SpannableString。它也可以给字符串的一部分着色。

SpannableString spannableString = new SpannableString("This is red text"); 
spannableString.setSpan(
          new ForegroundColorSpan(getResources().getColor(android.R.color.holo_red_light)), 
          0, 
          spannableString.length(), 
          0); 
Toast.makeText(this, spannableString, Toast.LENGTH_SHORT).show(); 
+0

以上单值** getColor(int)**方法已弃用,所以最好使用双值方法,如** getColor(int,theme)**。EX :: ** getColor(android.R.color.holo_red_light,getTheme ())** –

6

改变敬酒的背景颜色和烤面包的文字的背景色,最简单的方法:

View view; 
TextView text; 
Toast toast; 
toast.makeText(this, resId, Toast.LENGTH_SHORT); 
view = toast.getView(); 
text = (TextView) view.findViewById(android.R.id.message); 
text.setTextColor(getResources().getColor(R.color.black)); 
text.setShadowLayer(0,0,0,0); 
view.setBackgroundResource(R.color.white); 
toast.show();