Прохожу курс по Android, возникли проблемы с выполнение задания.
Нужно сделать простой светофор, по нажатию кнопки - меняется фон.
Вот 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));
}
}
}
А вот 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" />
Куча ошибок в коде, не знаю из-за чего
Большинство ошибок из-за того, что Вы вызываете метод findViewById(...) класса активити до выполнения метода setContentView(...).
Например, рассмотрим эту строчку:
Button redButoom = (Button) findViewById(R.id.buttonRed);
Здесь Вы объявляете поле класса redButoom и сразу же пытаетесь его инициализировать.
Выполнение этой строки происходит при создании экземпляра класса, в этот момент метод onCreate(...) активити еще не запустился (соответственно не запустился и метод setContentView(...)), в итоге, в методе findViewById(...) возникает исключение, так как пока еще не ясно, где именно искать элементы, так как setContentView(...) еще не отработал.
Искать какие-то элементы в разметке методом findViewById(...) можно только после того, как отработал метод setContentView(...), в противном случае, Вы получите исключение.
Как исправить – смотрите в соседнем ответе.
Сделайте инициализацию view в методе onCreate
private RelativeLayout mRealtiveLayout;
private TextView mTextView;
Button redButoom;
Button yellowButtom;
Button greenButtom;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRealtiveLayout=(RelativeLayout) findViewById(R.id.activity_main);
mTextView=(TextView) findViewById(R.id.textView);
redButoom=(Button) findViewById(R.id.buttonRed);
yellowButtom= (Button) findViewById(R.id.buttonRed);
greenButtom= (Button) findViewById(R.id.buttonGreen);
}
А еще у вас в разметке нет корневого layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<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" />
</RelativeLayout>
Продвижение своими сайтами как стратегия роста и независимости