如何从对话框片段打开新活动

我的程序在 MainActivity.java 中运行时打开一个 DialogFragment 类


我希望能够单击该对话框的“中性按钮”并打开一个新活动 SensorDataDisplay.java


我无法找到在我的按钮的 onClick 中引用上下文的正确方法。


package com.august.customtisensortagclient;


import android.app.AlertDialog;

import android.app.Dialog;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.os.Bundle;

import android.support.v4.app.DialogFragment;


import java.util.ArrayList;


public class GetInfoDialog extends DialogFragment {



    @Override

    public Dialog onCreateDialog(Bundle savedInstanceState) {






        final String thisWhichGetInfoDialog = ((MainActivity)getActivity()).getWhichGetInfoDialog();

        final ArrayList<String> thisScannedDevicesArrayList =

                ((MainActivity)getActivity()).getScannedDevicesArrayList();

        final int thisIsInLeftConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInLeftConnectedDeviceDisplay();

        final int thisIsInRightConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInRightConnectedDeviceDisplay();

        int thisIsInThisConnectedDeviceDisplay = 0;


        if (thisWhichGetInfoDialog == "Left") {

            thisIsInThisConnectedDeviceDisplay = thisIsInLeftConnectedDeviceDisplay;

        } else if (thisWhichGetInfoDialog == "Right")

            thisIsInThisConnectedDeviceDisplay = thisIsInRightConnectedDeviceDisplay;


        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setTitle(thisWhichGetInfoDialog + " Sensor Info");

        builder.setMessage("MAC Address: " + thisScannedDevicesArrayList.get(thisIsInThisConnectedDeviceDisplay));

        builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {



HUX布斯
浏览 127回答 2
2回答

人到中年有点甜

DialogFragmenthasgetActivity()和getContext()方法(它继承自Fragment),两者都适用于您的情况。如果您在从匿名类访问这些方法时遇到问题(不应该是这种情况),您可以使用GetInfoDialog.this.getActivity()语法。

HUH函数

getActivity() 返回片段附加到的 Activitybuilder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void onClick(DialogInterface dialog, int which) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Intent myIntent = new Intent(getActivity(), SensorDataDisplay.class);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; myIntent.putExtra("key", "TEST VALUE"); //Optional parameters&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; getActivity().startActivity(myIntent);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java