我怎样才能打开一个活动,并在android中传递一个上下文对象

时间:2016-03-22 04:41:27

标签: android

我正面临某种问题,我无法弄清楚原因。当我通过单击按钮调用函数“mapFound”时,会发生一些不好的事情。但我觉得它看起来很好。

package com.fva_001.flashvsarrow.com.fva_001;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MapFound extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.find_map);
}
// when I click this button, error happens
public void mapFound(View view){
    MapFoundDialog dialog = new MapFoundDialog(getApplicationContext());
    dialog.show();
}
}

这是我的MapFoundDialog类

package com.fva_001.flashvsarrow.com.fva_001;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.*;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;

public class MapFoundDialog extends Dialog {

public Context c;
public Button yes, no;

public MapFoundDialog(Context a) {
    super(a);
    // TODO Auto-generated constructor stub
    this.c = a;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    setContentView(R.layout.dialog_map_found);

// Here I want to open a new Activity, I think it has some problem too
    no = (Button) findViewById(R.id.btn_map_open);
    no.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new ButtonClick(getContext(), v);
            Intent entireMapIntent = new Intent(c, EntireMap.class);
            c.startActivity(entireMapIntent);
        }
    });
}
}

2 个答案:

答案 0 :(得分:0)

请通过提供Activity的上下文来检查,而不是应用程序上下文。请参阅以下代码,

package com.fva_001.flashvsarrow.com.fva_001;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MapFound extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.find_map);
    }
    // when I click this button, error happens
    public void mapFound(View view){
      MapFoundDialog dialog = new MapFoundDialog(MapFound.this);
      dialog.show();
    }
}

答案 1 :(得分:0)

上下文似乎存在问题。

public MapFoundDialog(Context a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}

你可以试试这个

 public void mapFound(View view){
  MapFoundDialog dialog = new MapFoundDialog(MapFound.this);
  dialog.show();
}