如何使用一个按钮实现EditText和保存编辑的文本?

时间:2018-07-29 05:58:48

标签: android buttonclick

按钮上的onclick监听器已实现

private void clickListener(){

    edit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getActivity(),"Edit is tapped",Toast.LENGTH_SHORT).show();

可以编辑文本

            tv_location.setFocusable(true);
            tv_location.setFocusableInTouchMode(true);

            sample.setFocusable(true);
            sample.setFocusableInTouchMode(true);

            edit.setPressed(false);

            edit.setText("Save");

存储更改的值并在编辑文本中显示

                final String location_txt = tv_location.getText().toString();
                tv_location.setText(location_txt);
                final String sample_text = sample.getText().toString();
                sample.setText(sample_text);

禁用编辑文本

                tv_location.setFocusable(false);
                tv_location.setFocusableInTouchMode(false);

                sample.setFocusableInTouchMode(false);
                sample.setFocusable(false);

                Toast.makeText(getActivity(),"Details have been saved",Toast.LENGTH_SHORT).show();


        }
    });
}

2 个答案:

答案 0 :(得分:0)

尝试一下:

private boolean isEditTextEnabled;

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isEditTextEnabled) {
                    String text = editText.getText().toString();
                   //save your text
                } else {
                    editText.setEnabled(true);
                    isEditTextEnabled = true;
                }
            }
        });

答案 1 :(得分:0)

将每个游览代码段设为私有方法:

private void enable() {
    tv_location.setFocusable(true);
    tv_location.setFocusableInTouchMode(true);
    sample.setFocusable(true);
    sample.setFocusableInTouchMode(true);
    edit.setPressed(false);
    edit.setText("Save");
}

private void disable() {
    tv_location.setFocusable(false);
    tv_location.setFocusableInTouchMode(false);
    sample.setFocusableInTouchMode(false);
    sample.setFocusable(false);
}

private void store() {
    final String location_txt = tv_location.getText().toString();
    tv_location.setText(location_txt);
    final String sample_text = sample.getText().toString();
    sample.setText(sample_text);
}

这是您的听众:

    edit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (sample.isEnabled()) {
                if (!sample.getText().toString().trim().isEmpty()) {
                    store();
                    disable();
                }
            } else {
                enable();
            }
        }
    });