0

Here is my onCreate method. I am trying to set the button to change the background of the background of the layout to be of a different color. However the findViewById is not able to pick up on the layout.

I fixed it by giving it another linear layout child but I would still like to know WHY it didnt work.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button button1 = (Button) findViewById(R.id.button1);
    LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
    //Below is code in question: Method is not resolved to type.
    button1.setOnClickListener(new OnClickListener(){


        public void onClick(View view) {
            layout.setBackgroundColor(Color.argb(100, 255, 0, 0));

        }
    });


}

HEre is my XML:
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" 
android:id="linearLayout1"
>


<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Button" />

</LinearLayout>
Jayizzle
  • 532
  • 1
  • 6
  • 24

3 Answers3

2

Your id is declared wrong.

It should be

android:id="@+id/linearLayout1"

instead of

android:id="linearLayout1"

And also Try using View.OnClickListener

button1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        layout.setBackgroundColor(Color.argb(100, 255, 0, 0));

    }
});
petey
  • 16,914
  • 6
  • 65
  • 97
codeMagic
  • 44,549
  • 13
  • 77
  • 93
1

The format should be:

android:id="@+id/linearLayout1"

The id indicates the type. The + indicates you are adding a new id.

Grimmace
  • 4,021
  • 1
  • 31
  • 25
0

The Id declaration that fails is the LinearLayout one you should change the linear layout as is in your button

<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" 
android:id="@+id/linearLayout1">


<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Button" />
</LinearLayout>
Eefret
  • 4,724
  • 4
  • 30
  • 46