簡體   English   中英

如何在android上動態更改按鈕和文本顏色

[英]How to change button and text color dynamically on android

如何動態/編程地更改按鈕文本顏色和按鈕形狀(矩形)?

如果main.xml中有一個id = 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>

您可以擁有自己的形狀文件。根據需要更改它。

您可以動態更改按鈕文本顏色

按鈕btnChangeTextColor =(按鈕)findViewbyId(btnChange); btnChangeTextColor.setTextColor(Color.BLUE);

基本上你必須遵循這個計划:

1)獲取要更改的對象的引用

findViewById(R.id.<your_object_id>);

2)將其強制轉換為對象類型

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

3)在對象“btnYourButton”上使用setter

4)重繪你的視圖(可能調用invalidate());

這取決於您何時希望更改發生。 我假設你的對象附有一個eventListener,在事件被觸發后你將執行你的更改。

@Override public boolean onTouchEvent(MotionEvent event){

    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;
}

您需要某種類型的偵聽器來偵聽要發生的事件,以及何時使用某些set方法更改形狀/文本顏色。

嘗試:

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

為了給出更有針對性的反饋,我需要知道你想要改變文本顏色和形狀的信號。 您能否通過動態更詳細地了解您的意思?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM