I am taking a course on Android, I have problems with the task.
It is necessary to make a simple traffic light, by pressing a button - the background changes.
Here is the main.class:
package com.example.opimand.oneswitchsemofor; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private final RelativeLayout mRealtiveLayout=(RelativeLayout) findViewById(R.id.activity_main); private final TextView mTextView=(TextView) findViewById(R.id.textView); Button redButoom=(Button) findViewById(R.id.buttonRed); Button yellowButtom= (Button) findViewById(R.id.buttonRed); Button greenButtom= (Button) findViewById(R.id.buttonGreen); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onClick(View view) { switch (view.getId()) { case R.id.buttonRed: mTextView.setText(R.string.red); mRealtiveLayout.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.colorRed)); break; case R.id.buttonYellow: mTextView.setText(R.string.yellow); mRealtiveLayout.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.colorYellow)); break; case R.id.buttonGreen: mTextView.setText(R.string.green); mRealtiveLayout.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.colorGreen)); } } } And here is main.xml:
<?xml version="1.0" encoding="utf-8"?> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello Kitty!" android:id="@+id/textView" /> <Button android:text="@string/green" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:layout_marginTop="148dp" android:id="@+id/buttonGreen" android:onClick="onClick"/> <Button android:text="@string/yellow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/buttonGreen" android:layout_alignRight="@+id/buttonGreen" android:layout_alignEnd="@+id/buttonGreen" android:layout_marginTop="17dp" android:id="@+id/buttonYellow" android:onClick="onClick"/> <Button android:text="@string/red" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="13dp" android:id="@+id/buttonRed" android:onClick="onClick" android:layout_below="@+id/buttonYellow" android:layout_alignLeft="@+id/buttonYellow" android:layout_alignStart="@+id/buttonYellow" />