繁体   English   中英

如何在 C# (Xamarin) 中使用 setOnTouchListener?

[英]How to use setOnTouchListener in C# (Xamarin)?

你能给我一个 C# 中 setOnTouchListener 的例子吗?

我试过这样,但我带来了一些错误。

Button1.setOnTouchListener(new View.OnTouchListener()
    {
        public boolean onTouch(View arg0, MotionEvent arg1)
        {
            x.Text = "1";
        }
    });

你要么使用Touch事件:

button1.Touch += (s, e) =>
{
    var handled = false;
    if (e.Event.Action == MotionEventActions.Down)
    {
        // do stuff
        handled = true;
    }
    else if (e.Event.Action == MotionEventActions.Up)
    {
        // do other stuff
        handled = true;
    }

    e.Handled = handled;
};

或者您可以显式实现IOnTouchListener接口(C# 没有匿名类)。 请注意,在实现 Java 接口时,您还需要从Java.Lang.Object继承,因为我们需要故事的 Java 端的句柄(这在我们使用Touch事件时显然不需要)。

public class MyTouchListener 
    : Java.Lang.Object
    , View.IOnTouchListener
{
    public bool OnTouch(View v, MotionEvent e)
    {
        if (e.Action == MotionEventActions.Down)
        {
            // do stuff
            return true;
        }
        if (e.Action == MotionEventActions.Up)
        {
            // do other stuff
            return true;
        }

        return false;
    }
}

然后设置它:

button1.SetOnTouchListener(new MyTouchListener());

请注意,使用后一种方法还需要您处理对要在OnTouchListener类中修改的对象的引用的传递,C# 事件OnTouchListener

编辑:作为旁注,如果您使用Touch事件或任何其他事件,请记住做一个好公民,并在您不再对接收它感兴趣时取消该事件。 最坏的情况是,如果您忘记取消挂接事件,则会因为无法清理实例而导致内存泄漏。

所以在第一个例子中,不要使用匿名方法:

button1.Touch += OnButtonTouched;

并记得解开它:

button1.Touch -= OnButtonTouched;
private Button Button1;

@Override
public void onCreate(Bundle savedInstanceState)
{       
    super.onCreate(savedInstanceState);

    Button1.setOnTouchListener(new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            if (event.getAction() == MotionEvent.ACTION_DOWN)
            {
                //do stuff
            }
            else if (event.getAction() == MotionEvent.ACTION_UP)
            {
                // do stuff
            }
            return false;
        }
    });
}

从你问的另一个问题来看,我猜你需要将 onTouch 侦听器移动到 onCreate 方法中

如何使用清单<object>回应 API - C# Xamarin<div id="text_translate"><p> I trying to convert this JSON API ( <a href="http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8" rel="nofollow noreferrer">http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8</a> ) to C# object here: <a href="https://json2csharp.com/" rel="nofollow noreferrer">https://json2csharp.com/</a></p><p> 我收到List<object> aladinModel { get; set; } List<object> aladinModel { get; set; }</p><p> 如何在我对 API 的回复中使用此列表 aladinModel:</p><pre> public async Task List<AladinModel> GetWeatherData(string query) { List<AladinModel> weatherData = new List<AladinModel>(); try { var response = await _client.GetAsync(query); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = JsonConvert.DeserializeObject<AladinModel>(content); } } catch (Exception ex) { Debug.WriteLine("\t\tERROR {0}", ex.Message); } return weatherData; }</pre><p> 此行不正确:</p><pre> public async Task List<AladinModel> GetWeatherData(string query)</pre><p> 如何在这里使用这个列表?</p><p> ================================================ =============</p><p> <strong>更新</strong></p><p> ================================================ =============</p><p> object class 看起来像:</p><pre> class ItemsAPI { public partial class RootAladinModel { [JsonProperty("aladinModel")] public AladinModel[] AladinModel { get; set; } } public partial class AladinModel { [JsonProperty("DATS")] public DateTimeOffset Dats { get; set; } [JsonProperty("TA")] public double Ta { get; set; } [JsonProperty("RH")] public double Rh { get; set; } [JsonProperty("WS")] public double Ws { get; set; } [JsonProperty("RR")] public double Rr { get; set; } [JsonProperty("SR")] public double Sr { get; set; } [JsonProperty("APRES")] public double Apres { get; set; } } }</pre><p> RestService class 看起来像:</p><pre> public async Task<List<AladinModel>> GetAladinData(string query) { List<AladinModel> weatherData = new List<AladinModel>(); try { var response = await _client.GetAsync(query); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = JsonConvert.DeserializeObject<List<AladinModel>>(content); } } catch (Exception ex) { Debug.WriteLine("\t\tERROR {0}", ex.Message); } return weatherData; }</pre><p> 但我收到错误:</p><pre> {Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[pizhevsoft.Models.ItemsAPI+AladinModel]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'aladinModel', line 1, position 15. at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x003a0] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x0006d] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x000db] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x0002d] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at pizhevsoft.Services.RestServiceAPI.GetAladinData (System.String query) [0x00151] in C:\Users\Admin\Desktop\pizhevsoft\pizhevsoft\pizhevsoft\pizhevsoft\Services\RestServiceAPI.cs:30 }</pre></div></object>

[英]How to use List<object> in response to API - C# Xamarin

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#setOnTouchListener建议 如何在Xamarin C#中使用setCompoundDrawables 如何在Xamarin C#for iOS中使用UIPageControl 是否可以将 C# 9 用于 Xamarin? Xamarin.Forms:如何在C#代码中使用自定义字体 如何在类构造函数中使用方法数据 c# xamarin 如何在 Xamarin.Z64502425319129281C3683CAE8A8 中的 XAML 中使用 C# 变量的值? C#Xamarin如何在类中使用现有List? 如何在C#Xamarin Forms中将绑定属性用作函数参数 如何使用清单<object>回应 API - C# Xamarin<div id="text_translate"><p> I trying to convert this JSON API ( <a href="http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8" rel="nofollow noreferrer">http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8</a> ) to C# object here: <a href="https://json2csharp.com/" rel="nofollow noreferrer">https://json2csharp.com/</a></p><p> 我收到List<object> aladinModel { get; set; } List<object> aladinModel { get; set; }</p><p> 如何在我对 API 的回复中使用此列表 aladinModel:</p><pre> public async Task List<AladinModel> GetWeatherData(string query) { List<AladinModel> weatherData = new List<AladinModel>(); try { var response = await _client.GetAsync(query); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = JsonConvert.DeserializeObject<AladinModel>(content); } } catch (Exception ex) { Debug.WriteLine("\t\tERROR {0}", ex.Message); } return weatherData; }</pre><p> 此行不正确:</p><pre> public async Task List<AladinModel> GetWeatherData(string query)</pre><p> 如何在这里使用这个列表?</p><p> ================================================ =============</p><p> <strong>更新</strong></p><p> ================================================ =============</p><p> object class 看起来像:</p><pre> class ItemsAPI { public partial class RootAladinModel { [JsonProperty("aladinModel")] public AladinModel[] AladinModel { get; set; } } public partial class AladinModel { [JsonProperty("DATS")] public DateTimeOffset Dats { get; set; } [JsonProperty("TA")] public double Ta { get; set; } [JsonProperty("RH")] public double Rh { get; set; } [JsonProperty("WS")] public double Ws { get; set; } [JsonProperty("RR")] public double Rr { get; set; } [JsonProperty("SR")] public double Sr { get; set; } [JsonProperty("APRES")] public double Apres { get; set; } } }</pre><p> RestService class 看起来像:</p><pre> public async Task<List<AladinModel>> GetAladinData(string query) { List<AladinModel> weatherData = new List<AladinModel>(); try { var response = await _client.GetAsync(query); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = JsonConvert.DeserializeObject<List<AladinModel>>(content); } } catch (Exception ex) { Debug.WriteLine("\t\tERROR {0}", ex.Message); } return weatherData; }</pre><p> 但我收到错误:</p><pre> {Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[pizhevsoft.Models.ItemsAPI+AladinModel]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'aladinModel', line 1, position 15. at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x003a0] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x0006d] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x000db] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x0002d] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at pizhevsoft.Services.RestServiceAPI.GetAladinData (System.String query) [0x00151] in C:\Users\Admin\Desktop\pizhevsoft\pizhevsoft\pizhevsoft\pizhevsoft\Services\RestServiceAPI.cs:30 }</pre></div></object>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM