簡體   English   中英

ConstraintLayout背景

[英]ConstraintLayout background

我試圖通過單擊按鈕來更改背景,但我無法在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”出錯:無法解析符號'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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM