简单的Hello World应用程序

时间:2015-08-17 19:52:01

标签: java android

当我尝试运行此代码时,它会说"错误:不是封闭的类:MainActivity"和"错误:缺少方法体或声明抽象。"这可能是一个非常简单的答案,但我是Android和Java编程的新手,对我的noob-ishness感到抱歉。

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


public class MainActivity2 extends Activity {

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

    Intent myIntent = new Intent (MainActivity.this, MainActivity2.class);
    startActivityForResult(myIntent, 0);

    Button btn = (Button) findViewById(R.id.button2);
    btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v);
    });
}


//Activities
public void onStart() {
    super.onStart();
    Log.i("TaskActivity", "MainActivity Started");
}

public void onResume() {
    super.onResume();
    Log.i("TaskActivity", "MainActivity Resumed");
}

public void onPause() {
    super.onPause();
    Log.i("TaskActivity", "MainActivity Paused");
}

public void onStop() {
    super.onStop();
    Log.i("TaskActivity", "MainActivity Stopped");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i("TaskActivity", "MainActivity Destroyed");
}

}

2 个答案:

答案 0 :(得分:2)

Intent()的第一个参数应该是当前(封闭)类。第二个参数是要加载的Activity。查看Developer Docs here

如果您想从MainActivity启动MainActivity2,请反转参数,以便Intent看起来像这样:

Intent myIntent = new Intent(MainActivity2.this, MainActivity.class);
startActivity(myIntent);

与您的方法相关的错误可能来自于在分配onClickListener时使用错误的语法。如果您尝试按下按钮启动MainActivity,则需要重新编写此部分:

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

答案 1 :(得分:1)

您需要实现onClick方法

btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v){
    }
});