如何通过hex更改java上的布局颜色?

时间:2016-06-05 09:08:19

标签: java android layout colors hex

我想根据用户的答案更改布局颜色。屏幕上有一个EditText。当用户在那里写一个十六进制代码时,背景颜色变为用户代码。

EditText hex;
Button ok;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    hex = (EditText)findViewById(R.id.hex);
      // User writes like that "#232323"

    ok = (Button)findViewById(R.id.btn);


    ok.setOnClickListener(new OnclickListener){
      //I want to make background that code
    }




}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

EditText hex;
Button ok;
RelativeLayout baselayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    hex = (EditText)findViewById(R.id.hex);
    ok = (Button)findViewById(R.id.btn);
    baseLayout=(RelativeLayout)findViewById(R.id.layout);

    ok.setOnClickListener(new OnclickListener){
        @Override
        public void onClick(View v)
           {
            String colorString=hex.getText().toString();

           //Validate Color before setting
            try {
                Color filteredColor = Color.parseColor(colorString);
                baseLayout.setBackgroundColor(filteredColor);
                } 
           catch (IllegalArgumentException iae) {
                // This color string is not valid
                }            
           }
    }
}