EditText get toString
This is my code but i can't fill my string with the value put in by the user.
I've tried a lot of solutions from other sites but it won't work.
package app.android.Mel
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.But开发者_JS百科ton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class RedFlashlightActivity extends Activity {
private EditText text;
private TextView myRecord;
private Button myButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.txtName);
myButton = (Button) this.findViewById(R.id.myButton);
myRecord = (TextView) findViewById(R.id.myRecord);
final String rec = text.getText().toString();
myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myRecord.setText(rec);
Toast.makeText(RedFlashlightActivity.this,rec, Toast.LENGTH_SHORT).show();
}
});
}
}
The point is that rec is created once at the activity creation time and doesn't change ever after( it is final ). Just replace
myRecord.setText(rec);
with
myRecord.setText(text.getText().toString());
myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String rec = text.getText().toString();
myRecord.setText(rec);
Toast.makeText(RedFlashlightActivity.this,rec, Toast.LENGTH_SHORT).show();
}
});
Move the rec = text.getText().toString()
into the OnClickListener
event handler class. Then it should work. Otherwise it will take a null value, because you're using the String rec
, which is constructed during the Activity
creation phase.
精彩评论