设置EditText的文本颜色

时间:2014-08-12 14:58:44

标签: java android

我有一个在EditText的上下文菜单上触发的对话框。对话框设置EditText的红色,绿色和蓝色的数量。问题是当我单击肯定按钮时发生运行时错误。上面的项目工作正常,他们在EditText中设置文本的颜色,但rgbDialog没有。

我认为问题出现在这里:

            etRed = (EditText)findViewById(R.id.etRed);
            etGreen = (EditText)findViewById(R.id.etGreen);
            etBlue = (EditText)findViewById(R.id.etBlue);

但我不知道如何初始化etRed,etGreen和etBlue。我认为我应该在findView之前放置一些东西,比如

etRed = (EditText)Dialog.findViewById(R.id.etRed);

但不知道是什么,因为一切都在同一个方法中发生(onContextItemSelected)

 @Override
public boolean onContextItemSelected(MenuItem item) {

    switch(item.getItemId()){
    case R.id.white:
        temp.setTextColor(Color.WHITE);
        break;
    case R.id.red:
        temp.setTextColor(Color.RED);
        break;
    case R.id.green:
        temp.setTextColor(Color.GREEN);
        break;
    case R.id.rgb:

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("choose the amount of red green and blue");

        LayoutInflater inflater = this.getLayoutInflater();

        dialogBuilder.setView(inflater.inflate(R.layout.colors, null));

        dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                etRed = (EditText)findViewById(R.id.etRed);
                etGreen = (EditText)findViewById(R.id.etGreen);
                etBlue = (EditText)findViewById(R.id.etBlue);

                red=etRed.getText().toString();
                green = etGreen.getText().toString();
                blue = etBlue.getText().toString();

                intRed = Integer.parseInt(red);
                intGreen = Integer.parseInt(green);
                intBlue = Integer.parseInt(blue);



                temp.setTextColor(Color.rgb(intRed, intGreen, intBlue));



            }
        });

        dialogBuilder.setNegativeButton("CANCEL", null);

        AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        break;
        default:
            break;
    }

    return super.onContextItemSelected(item);

}

EditText temp设置如下,适用于rgb

以上的项目
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {


        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context, menu);

        temp = (EditText)findViewById(v.getId());

        super.onCreateContextMenu(menu, v, menuInfo);
    }

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容从正确的布局调用findViewById:

View dialogView = inflater.inflate(R.layout.colors, null);
dialogBuilder.setView(dialogView );

当您在onClick中调用findViewById时,您可以拥有:

etRed = (EditText)dialogView.findViewById(R.id.etRed);
                etGreen = (EditText)dialogView.findViewById(R.id.etGreen);
                etBlue = (EditText)dialogView.findViewById(R.id.etBlue);

检查这是否有帮助。