[英]Increment in Array on button click with Xamirin
我正在嘗試使用帶有C#的Xamarin為Android創建一個簡單的應用程序,但是我只有C#的使用經驗。
我不太了解在網上找到的按鈕點擊,所以我不太了解自己在犯的錯誤。
我的應用程序就像是餐廳訂購應用程序。 它僅用於飲料atm。
我使用按鈕單擊將特定數組索引加1。
Button Cola = FindViewById<Button> (Resource.Id.Cola);
Cola.Click += array[0]+1;
編輯:我的想法是,當我單擊一個按鈕(例如“可樂”按鈕)時,它將使array [0]增加1。然后我有另一個按鈕來打印它。 因此,當我按可樂5次,然后按“完成”時,它將打印:可樂5
你為什么不這樣嘗試
//sample
int i=0;
Button click()
{
i++;
array[i];
}
有幾種不同的方法,其中一些方法比其他方法更簡單。 我已經提出了4種不同的方法來在Android上執行此操作。 請注意,如果調用Set方法,它將刪除所有其他方法(因為它是Set方法,而不是Add方法)。
[Activity (Label = "Increment", MainLauncher = true)]
public class MainActivity : Activity, View.IOnClickListener
{
private readonly int[] array = new int[4];
protected override void OnCreate(Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button cola = FindViewById<Button> (Resource.Id.myButton);
// will happen first (in order of assigned)
cola.Click += delegate
{
array [0]++;
};
// second
cola.Click += (sender, e) => array[1]++;
// third
cola.Click += HandleClick;
// if uncommented this will remove other events
//cola.SetOnClickListener (this);
}
void HandleClick (object sender, EventArgs e)
{
array [2]++;
}
public void OnClick(View v)
{
array [3]++;
}
}
您可以使用如下匿名函數:
Cola.TouchUpInside += delegate {
array[0]++;
};
您可以在以下站點上獲取更多信息: http : //docs.xamarin.com/recipes/ios/standard_controls/buttons/handle_clicks/
我看不到您要嘗試執行的操作,但是推薦的方法是:
final Button button = (Button) findViewById(R.id.Cola);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do your array increment here like array[1] or something?
}
});
看來您不太了解按鈕在android中的工作方式。 看一下Button類的setOnClickListener
方法,您將必須實現一個偵聽器,該偵聽器告訴Button在單擊時如何反應,並將偵聽器添加到您的按鈕中。
看這個例子:
http://developer.android.com/reference/android/widget/Button.html
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.