从按钮打开新活动

时间:2016-04-26 06:04:00

标签: android

我是开发新手,我正在尝试通过点击按钮创建一个新活动(新页面)。我真的被卡住了。这是我的主要活动的代码,但我无法摆脱错误...

package com.example.android.buttons;

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

public class MainActivity extends AppCompatActivity {

private static Button button;

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

public void OnClickButtonListener() {

    button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    Intent intentMain2Activity = new intent(MainActivity.this,Main2Activity.class);
                    startActivity(intent);
                }

            }

    );


}}

错误显示在startActivity(intent)行上...单词intent有红色下划线?标题为“无法解决符号”意图“

4 个答案:

答案 0 :(得分:3)

将意图更改为intentMain2Activity

 Intent intentMain2Activity = new Intent(MainActivity.this,Main2Activity.class);
 startActivity(intentMain2Activity);

答案 1 :(得分:1)

你也可以写成一行

button = (Button) findViewById(R.id.button1);
button.setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              startActivity(new Intent(MainActivity.this,Main2Activity.class));
            }

        }

);   

答案 2 :(得分:0)

这样做......

package com.example.android.buttons;

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

public class MainActivity extends AppCompatActivity {

private static Button button;

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

public void OnClickButtonListener() {

    button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    Intent intentMain2Activity = new Intent(MainActivity.this,Main2Activity.class);
                    startActivity(intentMain2Activity);
                }

            }

    );


}}

答案 3 :(得分:0)

 Intent intentMain2Activity = new Intent(MainActivity.this,Main2Activity.class);
                    startActivity(intentMain2Activity);