我正在进行练习,我现在很库存。我必须复制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);
}
});
}
}
问题在于您在onCreate()
内声明userinput
并将其制成final
,这使您无法稍后进行编辑。同样在CopyButton
click listener
内部,您正在为userinput
创建一个新的本地变量,其范围仅限于该侦听器。
将String userinput = new String();
移动到onCreate()
外,删除final
,然后将CopyButton
侦听器中的行更改为
userinput = UserInput.getText().toString();
您不应在CopyButton.setOnClickListener
内定义userinput
变量。将其定义为您的类或实例变量,以便您的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);
}
});
}