Android:使用 EditText 输入更改 ImageView 背景

标签 android background imageview android-edittext

我正在尝试编写我的第一个应用程序 - 一个简单的应用程序,用户在其中输入十六进制颜色代码 (EditText),点击回车键 (Button),然后 ImageView 的背景颜色更改为用户输入的十六进制代码。我如何看待它,我将不得不从 edittext 中获取文本,将 gettext 写入文件,然后编辑文件以在十六进制代码之前附加 0xAA,以便可以在 ImageView.setBackgroundColor(0xAA"HEXHEX") 中输入它。请让我知道我该怎么做,或者这是否是正确的方法。

到目前为止,这是我的 java(单击按钮时,背景颜色变为白色,清除将其恢复为黑色)

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

最佳答案

非常适合初学者。

使用Color.parseColor() .不要忘记先验证输入!

view.setBackgroundColor(Color.parseColor(edt.getText().toString()));

关于Android:使用 EditText 输入更改 ImageView 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9323278/

相关文章:

ios - 使用图像选择器将图像加载到两个 Collection View 单元格

android - 如何在 Android 布局中显示 Html 内容?

c# - 如何知道我的应用程序是在后台运行还是在前台运行?

java - 尝试设置 AlertDialog 但不断出现错误

wpf - 如何使用数据触发器更改 WPF 窗口背景?

ios - tablecell 背景仅显示自定义单元格,但显示自定义单元格使其无法选择

android - 动态添加ImageView到View

android - match_parent 高度内的 ImageView 居中图像

android - Google Awareness API、无效的 API key 、崩溃

javascript - 使用 javascript 获取手机区域设置