如何从对话框片段中打开新活动
Posted
技术标签:
【中文标题】如何从对话框片段中打开新活动【英文标题】:How to open a new activity from a dialog fragment 【发布时间】:2019-02-26 23:38:25 【问题描述】:我的程序在 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()
@Override
public void onClick(DialogInterface dialog, int which)
Intent myIntent = new Intent(?????, SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
?????.startActivity(myIntent);
);
builder.setNegativeButton("Done", new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int id)
// User cancelled the dialog
);
return builder.create();
【问题讨论】:
【参考方案1】:DialogFragment
具有getActivity()
和getContext()
方法(它继承自Fragment
),两者都适用于您的情况。如果您在从匿名类访问这些方法时遇到问题(不应该是这种情况),您可以使用 GetInfoDialog.this.getActivity()
语法。
【讨论】:
【参考方案2】:getActivity() 返回片段附加到的 Activity
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialog, int which)
Intent myIntent = new Intent(getActivity(), SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
getActivity().startActivity(myIntent);
);
【讨论】:
以上是关于如何从对话框片段中打开新活动的主要内容,如果未能解决你的问题,请参考以下文章