Cannot get widgets from main.xml specified in Java program

Created a very simple XML file to try a simple button widget. Main.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:background="@color/white">
  <TextView android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="@string/hello"/>
  <TextView android:text="Heading Text" 
            android:id="@+id/TextView01" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content">
  </TextView>
  <Button android:text="Button Text" 
          android:id="@+id/Button01" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content">
  </Button>
</LinearLayout>

Java program

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;


public class TestButton extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button myButton = (Button)findViewById(android.R.id.Button01);

    }
}

Error in 'Button' line:
Button01 cannot be resolved or is not a field

Any ideas what the main mistake I am making is :(: (.

+3
source share
1 answer
Button myButton = (Button)findViewById(android.R.id.Button01);

It is not right. It does not refer to automatically generated R.javafrom your project, it refers to a standard class android.R. It should be:

Button myButton = (Button) findViewById(R.id.Button01);
+7
source

Source: https://habr.com/ru/post/1766490/


All Articles