复制粘贴用户输入

时间:2017-02-27 16:30:40

标签: android onclick user-input gettext settext

我正在做练习,现在我有股票。 我必须复制Userinput,然后粘贴创建的字符串。 任何人都可以帮助我吗?

这是我的代码:

public class CopyPasteActivity extends AppCompatActivity {

    private Button CopyButton;
    private Button PasteButton;
    private EditText UserInput;
    private TextView PasteText;
    private final static String TAG = "CopyPasteActivity";

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_copy_paste);

        CopyButton = (Button) findViewById(R.id.copy_button);
        PasteButton = (Button) findViewById(R.id.paste_button);
        UserInput = (EditText) findViewById(R.id.user_input);
        PasteText = (TextView) findViewById(R.id.paste_text);

        final String userinput = new String();

        CopyButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "The button Copy was pressed");
               String userinput = UserInput.getText().toString();
            }
        });

        PasteButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "The button True was pressed");
                PasteText.setText(userinput);
            }
        });
    }
}

2 个答案:

答案 0 :(得分:2)

问题是,您在userinput内声明onCreate()并将其final设为CopyButton,这会阻止您稍后进行编辑。同样在click listener userinput内,您正在为String userinput = new String();创建一个新的局部变量,其范围仅限于该侦听器。

onCreate()移到final之外,移除CopyButton,然后将userinput = UserInput.getText().toString(); 收听者中的行更改为

{{1}}

答案 1 :(得分:0)

您不应在userinput内定义CopyButton.setOnClickListener变量。将其定义为您在侦听器外部的类或实例变量,以便PasteButton.setOnClickListener能够看到它。像这样:

String userinput;

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_copy_paste);

    CopyButton = (Button) findViewById(R.id.copy_button);
    PasteButton = (Button) findViewById(R.id.paste_button);
    UserInput = (EditText) findViewById(R.id.user_input);
    PasteText = (TextView) findViewById(R.id.paste_text);

    CopyButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "The button Copy was pressed");
            userinput = UserInput.getText().toString();
        }
    });

    PasteButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "The button True was pressed");
            PasteText.setText(userinput);
        }
    });
}