Java 在android中开始一个新的意图

Java 在android中开始一个新的意图,java,android,android-intent,android-activity,Java,Android,Android Intent,Android Activity,我正试图在班上开始一项新的活动。我不能打电话 startActivity(intent) 我需要为此扩展活动吗??如果是,怎么做 已解析,因此您可以对从上下文继承的类的任何对象调用它。通常,我们将现有活动称为startActivity 例如,这里我们有一个活动,它在自身上调用startActivity来启动另一个活动: /*** Copyright (c) 2012 CommonsWare, LLC Licensed under the Apache License, Version

我正试图在班上开始一项新的活动。我不能打电话

startActivity(intent)
我需要为此扩展活动吗??如果是,怎么做

已解析,因此您可以对从上下文继承的类的任何对象调用它。通常,我们将现有活动称为startActivity

例如,这里我们有一个活动,它在自身上调用startActivity来启动另一个活动:

/***
  Copyright (c) 2012 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    http://commonsware.com/Android
*/

package com.commonsware.android.exint;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class ExplicitIntentsDemoActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }

  public void showOther(View v) {
    startActivity(new Intent(this, OtherActivity.class));
  }
}
如果用户单击res/layout/main.xml中定义的按钮,则会调用showOther方法:


来看,这两种方法中的一种应该有效。如果你从另一个活动开始一个活动,你需要做的就是

Intent intent = new Intent(thisActivity.this, nextActivity.class);
startActivity(intent);
其中thisActivity是当前活动,nextActivity是您要启动的新活动

如果您没有上下文,例如,如果您创建了自己的不扩展活动的类,那么您仍然可以通过将其作为构造函数的参数来获取上下文

例如,在下面的示例中,构造函数获取对上下文的引用

public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<HashMap<String, Object>> films;

public ImageAdapter(Context c, ArrayList<HashMap<String, Object>> o) {
    mContext = c;
    mFilms = o;
}
此构造函数应在另一个类(可能是活动)中使用,该类已经引用了上下文:

new ImageAdapter(this, output);

如何使类继承上下文?永远不要扩展上下文。通过构造函数或方法参数传递一个。关键是活动扩展了上下文。@Bobdabiulder:如何使类继承上下文?-你没有。您已经有了一个上下文,例如您的活动。称之为星触觉。我对答案进行了编辑,以包含一个调用startActivity的示例。
public void startNewActivity() {
    Intent intent = new Intent(mContext, MainActivity.class);
    mContext.startActivity(intent);
}
new ImageAdapter(this, output);