从MAin活动中调用新活动

时间:2013-10-16 16:36:36

标签: android android-activity

我想,当您点击打开新屏幕(活动)但有问题时,新屏幕无法打开。对代码进行了哪些更改,以便打开新窗口?

package com.android.yalt;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

  Button btnny;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btnny = (Button) findViewById(R.id.ny);
    btnny.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.ny:
        startActivity(NY.class);
      break;
    default:
      break;
    }
  }

private void startActivity(Class<NY> class2) {
    // TODO Auto-generated method stub

}
}

1 个答案:

答案 0 :(得分:0)

你必须使用

startActivity(new Intent(getBaseContext(), NY.class));

Intent i = new Intent(getBaseContext(), NY.class);
startActivity(i);

或以方法格式:

 public void startMyActivity(Class activityToStart){
startActivity(new Intent(getBaseContext(), activityToStart.class));
    }

正如旁注一样,如果有人愿意,可以用自己的上下文替换getBaseContext()。 startActivity(new Intent(yourOnGoingActivityGoesHere.this, yourClassGoesHere.class));

另外作为实用程序:

/*This is not tested but should work */
public class AndroidUtility(){
/**
 *Usage: AndroidUtility.startMyActivity(MainActivity.this, NY.class);
 */
public static void startMyActivity(Activity onGoingActivity, Class activityToStart){
onGoingActivity.startActivity(new Intent(onGoingActivity.getBaseContext(), activityToStart.class));


   }
}

在您的情况下,最简单的是:

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.ny:
          startActivity(new Intent(getBaseContext(), NY.class));
      break;
    default:
      break;
    }
  }