约束布局背景

11

我试图通过点击按钮来改变背景,但是我无法在Java代码中识别Constraint Layout。

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));
}
}

在主活动中,第18行出现了一个错误:“constraintLayout”无法解析符号。 如何更改背景颜色?

1个回答

10

您的约束布局中未添加 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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接