Hussein Reda AlBehary Hussein Reda AlBehary - 1 year ago 744
Android Question

'MyFirstApp.Resource.Id' does not contain a definition for 'myButton' (CS0117) (MyFirstApp)

Main Activity I'm naming my project "MyFirstApp"

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace MyFirstApp
{
[Activity (Label = "MyFirstApp", MainLauncher = true)]
public class MainActivity : Activity
{
int count = 1;

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 button = FindViewById<Button> (Resource.Id.myButton);

button.Click += delegate {
button.Text = string.Format ("{0} clicks!", count++);
};
}
}
}


Layout res/layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText
android:id="@+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Enter Message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:id="@+id/button_send" />
</LinearLayout>


Strings

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
<string name="action_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>


Please help me i'm beginner in android development
if there is anything not clear i'll try to add more details
i'm using Xamarin for developing

Thanks

Answer Source

add the attribute:

android:id="@+id/myButton"

to your button in the layout xml file.

Then in your Activity you can find your button like this:

Button button = (Button) findViewById(R.id.myButton);

Instead of:

Button button = FindViewById<Button> (Resource.Id.myButton);

Update: Well, the findViewById I propsed was plain Android, not sure how it works in Xamarin, but for sure your button needs an id in the xml

Update 2: Actually you already had and Id for your button, but it is not myButton, it is button_send ==> so you may want to use that one instead myButton