2012年4月27日金曜日

半透明の程度を動的に変更する

半透明の程度を動的に変更する

半透明の程度の値(alpha値)を、何か1個の値で固定したままにするのであれば、その値をxmlファイルに設定すれば良い。
この記事では、利用者の操作等により、alpha値が任意の値に動的に変更・表示できる方法を示す。

この場合、透明のActivityにはconfiguration changeが発生しないという現象があるので注意して頂きたい。

手順概要
1 アプリ(又は任意のActivity)を、完全な透明であるように設定する。
2 任意のタイミングで、任意の半透明の値に設定・表示する。

1 アプリ(又は任意のActivity)を、完全な透明であるように設定する。
処理対象ファイル:AndroidManifest.xml
書き加えるコマンド:android:theme="@android:style/Theme.Translucent"
書き加える場所:アプリ全体を半透明化するのであれば、<application>の属性として書く。任意のActivityだけに施すのであれば、<activity>の属性として書く。
sample code:アプリ全体を半透明化する場合、次のとおりである。
<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="jp.Androyer.Transparent"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Translucent"
        >
        <activity
            android:name=".TransparentActivity"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

2 任意のタイミングで、任意の半透明の値に設定・表示する。
Java codeの中で、setBackgroundColorメソッドを使う。
sample codeは次のとおりである。
public class TransparentActivity extends Activity
    implements
    OnClickListener
    {
    Button bu;
    TextView tv;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        bu = (Button)findViewById(R.id.Button);
        bu.setOnClickListener(this);
        
        int i;
        char c = '亜';
        StringBuilder sv;
        
        //適当に文字列を作成・表示する。
        sv = new StringBuilder();
        for(i=0; i<800; i++, c++) sv.append(c);
        tv = (TextView)findViewById(R.id.Text);
        tv.setText(sv);
        //本アプリの後ろの他のアプリが完全に見える状態で表示される。
        //ただし、文字は白色で表示される。
    }
    
    @Override
    public void onClick(View v) {
        if(v==bu){
            //任意の色の背景色にする。ここでは桃色の半透明にする。
            tv.setBackgroundColor(Color.argb(0x66, 0xff, 0, 0xff));
        }
    }
}

参考:上記sample codeで使用したレイアウト用のxml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    >
    <Button
        android:id="@+id/Button"
        android:text="@string/Button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >
    </Button>
    <TextView
        android:id="@+id/Text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >
    </TextView>
</LinearLayout>

0 件のコメント:

コメントを投稿