gpt4 book ai didi

java - ConstraintLayout背景

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:52 26 4
gpt4 key购买 nike

我试图通过单击按钮来更改背景,但我无法在 Java 代码中识别约束布局。

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
android:background="@color/red"
tools:context="frekzok.trafficlight.MainActivity">

//here are some button options

</android.support.constraint.ConstraintLayout>

MainActivity.java:

package frekzok.trafficlight;

import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
private ConstraintLayout mConstraintLayout;
private TextView mInfoTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mConstraintLayout =
(ConstraintLayout)findViewById(R.id.constraintLayout);
mInfoTextView = (TextView)findViewById(R.id.textView2);}

public void onRedButtonClick(View view) {
mInfoTextView.setText(R.string.red);
mConstraintLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.red));
}
public void onYellowButtonClick(View view) {
mInfoTextView.setText(R.string.yellow);
mConstraintLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.yellow));
}
public void onGreenButtonClick(View view) {
mInfoTextView.setText(R.string.green);
mConstraintLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.green));
}
}

在主 Activity 中,第 18 行,“constraintLayout”上出现错误:无法解析符号“constraintLayout”如何更改背景颜色?

最佳答案

您没有将 ID 添加到约束布局中。尝试修改您的 xml 文件以包含它:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
android:id="@+id/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"
android:background="@color/red"
tools:context="frekzok.trafficlight.MainActivity">
</android.support.constraint.ConstraintLayout>

关于java - ConstraintLayout背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45348491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com