我正在尝试编写我的第一个应用程序 - 一个简单的应用程序,用户输入十六进制颜色代码(EditText),点击输入(按钮),然后将ImageView的背景颜色更改为用户输入的十六进制代码。我怎么看,我必须从edittext获取文本,将gettext写入文件,然后编辑文件以在十六进制代码之前附加0xAA,以便可以在ImageView.setBackgroundColor(0xAA“HEXHEX”)中输入。请让我知道如何做到这一点,或者这是否是正确的方法。
这是我的java到目前为止(按钮点击,bg颜色变为白色,清除将其恢复为黑色)
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ImageView;
import android.view.View;
public class ChkhexActivity extends Activity {
private EditText hex;
private Button chk;
private Button clear;
private ImageView view;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
hex = (EditText)findViewById(R.id.hex);
chk = (Button)findViewById(R.id.chk);
clear = (Button)findViewById(R.id.clear);
view = (ImageView)findViewById(R.id.view);
chk.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ Chk(); }});
clear.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ Clear(); }});
}
private void Chk()
{
view.setBackgroundColor(0xFFffffff);
}
private void Clear()
{
hex.setText("");
view.setBackgroundColor(0xFF000000);
}
}
答案 0 :(得分:1)
非常适合初学者锻炼。
使用Color.parseColor()。不要忘记首先验证输入!
view.setBackgroundColor(Color.parseColor(edt.getText().toString()));
答案 1 :(得分:0)
every time u want to change the color of imageview based on text entered in edittext.so u cant fix it like this
view.setBackgroundColor(0xFFffffff);
u have to get the text from edittext.some example like this..
public class test extends Activity{
private EditText ed;
private Button btn;
private ImageView iv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
ed=(EditText)findViewById(R.id.editText1);
btn=(Button)findViewById(R.id.button1);
iv=(ImageView)findViewById(R.id.imageView1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String value=ed.getText().toString();
iv.setBackgroundColor(Color.parseColor(value));
}
});
}
}
the edittext text u entered can be like hex format example like #B0171F,#fafad2,..