2011-11-03 23 views
6

ボタンテキストの色とボタンの形状(四角形)を動的に/プログラムで変更する方法はありますか?ボタンとテキストの色を動的に変更する方法

1)あなたは

findViewById(R.id.<your_object_id>); 

2)は、オブジェクト型

Button btnYourButton = (Button) findViewById(R.id.<your_object_id>); 

3にキャスト変更したいオブジェクトへの参照を取得します:

+3

saerch http://stackoverflow.com/questions/4755871/how-to-set-image-button-backgroundimage-異なる州のための/ 4755934#4755934 – ingsaurabh

答えて

11

あなたがIDを持つあなたのmain.xmlにあるボタンを使用している場合は、次のように= Button1のは、あなたがそれを使用することができます。

setContentView(R.layout.main); 

Button mButton=(Button)findViewById(R.id.button1); 
mButton.setTextColor(Color.parseColor("#FF0000")); // custom color 
//mButton.setTextColor(Color.RED); // use default color 
mButton.setBackgroundResource(R.drawable.button_shape); 

R.drawable.button_shape(button_shape.xml):

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
    <gradient 
     android:startColor="#70ffffff" 
     android:centerColor="#70ffffff" 
     android:endColor="#70ffffff" 
     android:angle="270" /> 
    <corners 
     android:bottomRightRadius="8dp" 
     android:bottomLeftRadius="8dp" 
     android:topLeftRadius="8dp" 
     android:topRightRadius="8dp"/> 
</shape> 

あなたはあなたの必要に応じて独自の形状ファイルを変更することができます。

1

は、基本的には、スキームに従わなければなりません)オブジェクト "btnYourButton"にsetterを使用

4)ビューを再描画する(おそらくinvaliを呼び出す日付());

変更がいつ発生するかによって異なります。あなたのオブジェクトにeventListener が添付されていると仮定し、イベントが発生した後で変更を実行します。

0

イベントが発生するのをリッスンするリッスナーが必要です。また、いくつかのsetメソッドを使用してシェイプ/テキストの色を変更するときに必要になります。

試してみてください。

http://developer.android.com/reference/android/view/View.OnClickListener.html

私はあなたがテキストの色や形状を変更するために持っていたいもの信号を知っている必要があるだろう、より尖ったフィードバックを与えること。あなたは、あなたが動的に変化を意味するかどうかについてもっと詳しく説明できますか?

4

あなたが動的に

ボタンbtnChangeTextColor =(ボタン)findViewbyId(btnChange)のようなボタンのテキストの色を変更することができます。 btnChangeTextColor.setTextColor(Color.BLUE);

0

@Override パブリックブールonTouchEvent(MotionEventイベント){このような質問のためのSO

if (event.getAction() == MotionEvent.ACTION_DOWN) { 

     start_x = event.getX(); 
     start_y = event.getY(); 

    } else if (event.getAction() == MotionEvent.ACTION_MOVE) { 

     setTitle(event.getX() + "y pos" + event.getY()); 
     RelativeLayout layout = (RelativeLayout) findViewById(R.id.lay); 

     layout.setBackgroundColor(Color.rgb((int) start_x, (int) start_y, 0)); 
    } else if (event.getAction() == MotionEvent.ACTION_UP) { 



    } 
    return true; 
} 
関連する問題