新活动没有响应

0 java android android-layout android-activity

我一直试图弄清楚我自己有什么问题,但是第二个活动就是按钮点击不开始,没有错误信息,没有空白页,好像按钮不起作用,我错过了明显的东西?

public class createMessage extends AppCompatActivity {
    public static final String EXTRA_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_message);
    }

    Button b ;

    public void clickSend(){
        b = (Button) findViewById(R.id.send);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(createMessage.this,receiveMessage.class);
                startActivity(intent);
                EditText editText = (EditText) findViewById(R.id.typeMessage);
                String message = editText.getText().toString();
                intent.putExtra(EXTRA_MESSAGE, message);
                startActivity(intent);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

第二项活动:

public class receiveMessage extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_message);


        // Get the Intent that started this activity and extract the string
        Intent intent = getIntent();
        String message = intent.getStringExtra(createMessage.EXTRA_MESSAGE);

        // Capture the layout's TextView and set the string as its text
        TextView textView = (TextView) findViewById(R.id.showMessage);
        textView.setText(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

tau*_*aug 8

你必须clickSend()onCreate()方法中调用方法.

然后只有onClickListener意志工作.

并删除startActivity(intent)两次调用.

改变createMessage类的代码如下

public class createMessage extends AppCompatActivity {
    public static final String EXTRA_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_message);
        clickSend();
    }

    Button b ;

    public void clickSend(){
        b = (Button) findViewById(R.id.send);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(createMessage.this,receiveMessage.class);
                EditText editText = (EditText) findViewById(R.id.typeMessage);
                String message = editText.getText().toString();
                intent.putExtra(EXTRA_MESSAGE, message);
                startActivity(intent);
            }
        });
     }
    }
Run Code Online (Sandbox Code Playgroud)

  • 在你的回答中还包括OP不需要调用`startActivity(intent);`两次. (3认同)