動態輸入String改變TextView的顏色(String轉換成Color)

功能描述:EditText手動輸入字符串“#FFFFFF”等,改變TextView字體的顏色。


方法:

int android.graphics.Color.parseColor(String colorString)

public static intparseColor (String colorString)

Added in API level 1

Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are:#RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuschia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal' 

紅字部分是函數parseColor 參數支持的類型。如果String是“#asffds”等不能解析的值,程序不會崩潰,log打印出IllegalArgumentException。

代碼非常簡單,如下:

public class MainActivity extends Activity {

    private EditText input;
    
    private TextView text;
    
    private Button change;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        input = (EditText) findViewById(R.id.input_color);
        text = (TextView) findViewById(R.id.text);
        change = (Button) findViewById(R.id.change);
        change.setOnClickListener(listener);
    }
    
    View.OnClickListener listener = new View.OnClickListener() {
        
        @Override
        public void onClick(View v) {
            String s = input.getText().toString();
            int color =  Color.parseColor(s);
            text.setTextColor(color);
        }
    };
    
}


源代碼:http://download.csdn.net/detail/liucaoye/8128019



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章