过程.Xamarin窗体空引用上的Start()



每次通过DB收到的文本是链接时,我都试图在屏幕上创建一个按钮。因此,当按下该按钮时,将用户重定向到相应的网页。然而,即使文本不是null,我也会得到以下错误:System。NullReferenceException:"对象引用未设置为对象的实例。"我在上使用Xamarin Forms。NET 6和Visual Studio社区2022。我不知道这是不是简单的事情,因为我从来没有真正尝试过做这样的事情。

private Button GetButtonLinkSolution(SolutionDTO solution)
{
Button btnLink = new Button();
btnLink.Style = (Style)Application.Current.Resources["btnNiveis"];
btnLink.BorderColor = Color.FromHex("#2b2b80");
btnLink.Text = "Answer (click here)";
string textBotao = "";
for (int i = 0; i < solution.Text.Length; i++)
{
textBotao = textBotao + String.Concat(solution.Text[i]);
}
btnLink.Clicked += (sender, args) => ButtonLink_Clicked(sender, args, textBotao);
return btnLink;
}
private void ButtonLink_Clicked(object sender, EventArgs args, string textBotao)
{
Process.Start(textBotao);
}```

因此,在您的代码中有很多我不理解的地方,让我感到困惑,比如从按钮事件中调用单独的事件来分配字符串。

例如:

string textBotao = "";
for (int i = 0; i < solution.Text.Length; i++)
{
textBotao = textBotao + String.Concat(solution.Text[i]);
}

这段代码将把Text数组中的所有项循环成一个字符串,然后将其分配给textBotao,我甚至不确定它最后是否是有效的URL。无论如何,我猜你要做的是打开一个URL。

现在,如果你有Xamarin Essentials(可能有(:

然后您应该使用以下Essentials API:https://learn.microsoft.com/en-us/xamarin/essentials/open-browser?tabs=android

对于Android 11 plus,请确保您的清单中有此查询:

<queries>
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="http"/>
</intent>
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https"/>
</intent>
</queries>

然后像这样打开浏览器:

var textBotaoUri = new System.Uri(textBotao);
await OpenBrowser(textBotaoUri);

OpenBrowser如下所示:

public async Task OpenBrowser(Uri uri)
{
try
{
await Browser.OpenAsync(uri, BrowserLaunchMode.SystemPreferred);
}
catch(Exception ex)
{
// An unexpected error occured. No browser may be installed on the device.
}
}

这里还有一些自定义选项:https://learn.microsoft.com/en-us/xamarin/essentials/open-browser?tabs=android#customization

最新更新