将EditText中的文本发送到第二个活动

时间:2015-10-10 14:09:12

标签: java android

我正在尝试从EditText小部件中获取文本并将其发送到第二个活动,这是我直到现在所写的内容:

package example.antonio.anexample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.EditText;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EditText etxt = new EditText(this);
        etxt.setHint("Write something");
        Button btn = new Button(this);
        btn.setText("Send");

        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Editable input = etxt.getText();
                Intent i = new Intent(MainActivity.this, SecondActivity.class);
                i.putExtra("message", input.toString());
                startActivity(i);
            }
        });


        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.addView(etxt);
        layout.addView(btn);
        setContentView(layout);
    }

}

但是因为你可以成像它不能编译,我怎样才能从内部类中访问etxt变量?

1 个答案:

答案 0 :(得分:2)

制作etxt final,以便您可以在内部课程

上访问它
    final EditText etxt = new EditText(this);
    etxt.setHint("Write something");
    Button btn = new Button(this);
    btn.setText("Send");

    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String input = etxt.getText();
            Intent i = new Intent(MainActivity.this, SecondActivity.class);
            i.putExtra("message", input.toString());
            startActivity(i);
        }
    });