我的错误是:“找不到符号变量activity_main”如何解决?此代码用于更改 android java 代码的屏幕光线,我使用了不同的方法,但无法解决它。
package com.example.lightbluered;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends 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.RED);
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);
}
}
});
}
}
和活动主要 XML 代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.532"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.524" />
</androidx.constraintlayout.widget.ConstraintLayout>
怎么解决呢?
根据此更改您的布局:
<?xml version="1.0" encoding="utf-8"?>
<Relativelayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/relative"
>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.532"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.524" />
</Relativelayout>
然后改变这一行
RelativeLayout bgElement = (RelativeLayout) findViewById(R.id.activity_main);
到
RelativeLayout bgElement = (RelativeLayout) findViewById(R.id.relative);
不需要relativelayout
在onclick方法中再次定义
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句