我正在做练习,现在我有股票。 我必须复制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);
}
});
}
}
答案 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);
}
});
}