2013年3月19日火曜日

xmlで背景を変更(android:shape=)

今回はボタンやテキストビューの
背景をxmlファイルで指定する方法を説明します。

グラデーションをかけたり、ボタンの周りに線を引いたりと、
割と使えます。

イメージ的にはCSS(スタイルシート)のような使い方です。

■事前準備
resフォルダの中のdrawableにxmlファイル
grad_button.xml
text_customer.xml
を作成しておいてください

■サンプル
●メインアクティビティー
package com.example.customlayout;

import android.os.Bundle;
import android.app.Activity;

import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

    private int iWC = LinearLayout.LayoutParams.WRAP_CONTENT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //レイアウトの生成
        LinearLayout layout=new LinearLayout(getApplicationContext());
        //上から下にオブジェクトを配置するよう設定
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);
        
        //テキストビューを画面に追加する
        TextView tv = new TextView(getApplicationContext());
        tv.setBackgroundResource(R.drawable.text_customer);
        tv.setText("テキストだよ");
        //画面位置の設定
        tv.setLayoutParams(new LinearLayout.LayoutParams(iWC,iWC));
        
        //ボタンを画面に追加する
        Button oBtn = new Button(getApplicationContext());
        oBtn.setBackgroundResource(R.drawable.grad_button);
        oBtn.setText("ボタンだよ");
        oBtn.setLayoutParams(new LinearLayout.LayoutParams(iWC,iWC));
        
        //テキストビューとボタンをレイアウトに追加する
        layout.addView(tv);
        layout.addView(oBtn);
    }
}
●grad_button.xml


  
    
      
      
      
      
    
  


●text_customer.xml


  
   
      
      
      
    
  

■実行結果

はダサかったので、画像の添付はありません。。。
とりあえず綺麗なグラデーションが掛っているのがわかると思います。


<shape android:shape=~>
これで、背景の形を指定しています。

<shape android:shape="oval">          だえん
<shape android:shape="rectangle">  四角形
<shape android:shape="line">      線形
<shape android:shape="ring">   まん丸

また、今回はItemタグはそのまま記載されていますが、

<item android:state_pressed="true" >
とすると、ボタンを押したときのデザインを記載できます。

指定できるパラメータはCSSと同じような感じで、
だいたい上手くいくので、いろいろ試してみてください。



デザイン的なのは全般的に苦手ですし、
実用性も感じないので、いまいちモチベーションが上がらないのですが。。。

デザイン性の高いものはユーザーからの機能性に関する不満も減ると、Androidの講習で有名な方がおっしゃていました。(本当かよ!!)




0 件のコメント:

コメントを投稿