findViewById更改Android Studio背景色

我在尝试对android网站上的教程进行一些修改时遇到一些问题。在学习本教程之后,我没有任何问题,但是当尝试进行一些细微修改以进一步了解约束,视图,布局等时,我发现自己陷入了困境。

到目前为止,除了尝试将颜色发送到更改背景颜色的新活动之外,我几乎与本教程完全相同。

到目前为止,我的问题是找到要定位到所述窗口的ID。在原始教程中,“ R.id.textView”定位了约束树的一个组件,但是,我已经有了背景色,我认为我可以使用windows / constraint ID来更改颜色。

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_color);

        Intent intent = getIntent();
        String hexValue = intent.getStringExtra(Mainactivity.EXTRA_MESSAGE);

        RelativeLayout layout = (RelativeLayout) findViewById(R.layout.activity_main);
        layout.setBackgroundColor(parseColor("#" + hexValue));
    }

到目前为止,我已经浏览了相当多的文档,但是它们又庞大又详细,因此我可能正在寻找错误的搜索词。

任何帮助表示赞赏!谢谢!

================================================ =============

更新后的Mainactivity代码。

package com.example.color;

import androidx.appcompat.app.AppCompatactivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import static android.graphics.Color.parseColor;

public class Mainactivity extends AppCompatactivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void changeColor(View view) {
        Intent intent = new Intent(this,Mainactivity.class);
        EditText editText = (EditText) findViewById(R.id.editText);
        String hexValue = editText.getText().toString();
        ConstraintLayout conlay = (ConstraintLayout) findViewById(R.id.screen);
        conlay.setBackgroundColor(parseColor("#" + hexValue));
        startactivity(intent);
    }
}

这开始起作用,但是我决定删除第二个活动,因为它的响应不佳。现在,我可以更改颜色,但是它不会更改主屏幕的背景色,并且/或者它不会持久。但是颜色现在确实改变了!所以,谢谢你到目前为止我所拥有的!

iCMS 回答:findViewById更改Android Studio背景色

使用自定义按钮将具有新颜色的按钮保存在您的文件夹中,而不是发送新颜色,并且在更改Acitivity时,只需在新活动功能中更改底部背景ID

但是我相信错误是您将十六进制值另存为字符串...

,

要查找布局的ID,请在xml中查找以下行。

android:id="@+id/your_layout_id"

然后,您可以更改以下布局的背景颜色。

//In your example your_layout_id = screen
RelativeLayout mRelativeLayout = (RelativeLayout)findViewById(R.id.your_layout_id);
mRelativeLayout.setBackgroundColor(Color.RED);

此外,我可以看到您的布局是约束布局,而不是相对布局。

因此您更改背景的代码应如下所示。

ConstraintLayout mConstraintLayout = (ConstraintLayout)findViewById(R.id.screen);
mConstraintLayout.setBackgroundColor(Color.RED);
本文链接:https://www.f2er.com/1990122.html

大家都在问