Search code examples
androidandroid-studioandroid-relativelayoutandroid-constraintlayout

Unable to create ID value resource for my android app


Where setContentView (R.laout.activity_main) works ... findViewByID does not, it says cant resolve and this is a basic app to change the BackgroundColor.

      AppCompatActivity {
     Button button;
     @Override
    protected void onCreate(Bundle 
     savedInstanceState) {
      super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     RelativeLayout bgElement = (RelativeLayout) 
      findViewById(R.id.activity_main);
       bgElement.setBackgroundColor(Color.WHITE);
      myButtonListenerMethod();
       }
     public void myButtonListenerMethod() {
      button = (Button)findViewById(R.id.button);
       button.setOnClickListener(new 
        View.OnClickListener() {
        @Override
     public void onClick(View v) {
      RelativeLayout bgElement = 
     (RelativeLayout)findViewById(R.id.activity_main);
      int color = ((ColorDrawable) 
    bgElement.getBackground()).getColor();
     if (color == Color.RED) {
    bgElement.setBackgroundColor(Color.BLUE);
    }
    else {
    bgElement.setBackgroundColor(Color.RED);
    }
    }
    });
   }
   }````

Solution

  • This is wrong RelativeLayout bgElement = (RelativeLayout) findViewById(R.id.activity_main); You are mistaken the layout file for an id.

    Fix it this way.

    RelativeLayout bgElement = findViewById(R.id.relative_layout_id);
    

    Replace relative_layout_id with the correct relative layout id.