繁体   English   中英

findViewById 更改背景颜色 Android Studio

[英]findViewById to change background color Android Studio

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

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

到目前为止,我的问题是找到针对 window 的 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);
    }
}

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

不要发送新颜色,而是使用自定义按钮将带有新颜色的按钮保存在文件夹中,并且在更改 Acitivity 时,只需更改新活动 function 中的底部背景 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM