2011年5月23日月曜日

[Android] アプリの背景色を設定した後のToastの背景色がおかしくなるのをなんとかする。

Androidのアプリを作成した際に
背景色などを固定したとする。

style.xml

  1. <resources>  
  2.     <style name="BackStyle">  
  3.         <item name="android:background">#C8FFC8</item>  
  4.         <item name="android:textColor">#0066ff</item>  
  5.      
  6.       
  7. </style>  
  8. </resources>  

androidManifest.xml(一部)

  1. <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@style/BackStyle">  
  2.         <activity android:configchanges="orientation" android:label="@string/app_name" android:name=".MainActivity">  
  3.             <intent-filter>  
  4.                 <action android:name="android.intent.action.MAIN">  
  5.                 <category android:name="android.intent.category.LAUNCHER">  
  6.             </category>  
  7.         </action>  
  8.           
  9.     </intent-filter>  
  10. </activity></application>  


これで背景色と文字色がアプリケーション単位で固定できるのですが、
うっかりToastまでこんなことになります。






















Toastの透過の問題なのかどうだかしりませんが、
コードはこんな感じのいたって普通。
  1. Toast.makeText(this"ほめてくれてありがとう", Toast.LENGTH_LONG).show();  

この1行だけであの大惨事・・・。
リファレンスにも特にToastに関することはなにもかかれていない。
それでもなんとか、Toastに「setView()」なるものを発見したので
諦めて1つViewを作成することにしました。

といっても、XMLには詳しくないので
コードでゴリゴリと。

こんなメソッドを作成。

  1. public View makeToast(String message) {  
  2.   TextView text = new TextView(this);  
  3.   text.setBackgroundColor(Color.WHITE);  
  4.   text.setText(message);  
  5.   text.setPadding(5555);  
  6.     
  7.   return text;  
  8.  }  

これだとstring.xmlが使えなくてしょうもないので書き変えてみる。
  1. public View makeToast(int messageId){  
  2.   TextView text = new TextView(this);  
  3.   text.setBackgroundColor(Color.WHITE);  
  4.   text.setText(messageId);  
  5.   text.setPadding(5555);  
  6.     
  7.   return text;  
  8.  }  

で、実際にToastを使用するところでこうする。
  1. Toast toast = new Toast(this);  
  2.    toast.setView(makeToast("ほめてくれてありがとう"));  
  3.    toast.show();  

string.xmlに定義している文字列を使うときはこうする。
  1. Toast toast = new Toast(this);  
  2.    toast.setView(makeToast(R.string.talk_atama1));  
  3.    toast.show();  
(ID名のセンスがない。すまん)

要するにViewを継承しているTextViewを自前で作成して
ToastのViewとしてセットして表示しているだけです。
実際にはこんな感じのポップアップになります。




















純粋なToastみたいな角丸なものにするには
もうちょっとこったものにしたりとかする必要があるのですが、
応急処置としてこちらをつくってみました。
いくらなんでも背景色にとけこんだToastがでてくるとがっかりだよね、ということで。

0 件のコメント:

コメントを投稿