繁体   English   中英

如何通过不同的活动更改视图的背景色

[英]How to change the background color on a view from different activity

当我在MainActivity中找到ViewById()时,我需要更改导航标题上的背景颜色。

这是导航标题

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nav_second_header_bg"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="#00aeef"
    android:gravity="bottom"
    android:orientation="vertical"
    android:padding="12dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/school"
        android:layout_width="wrap_content"
        android:layout_height="88dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:src="@drawable/schatkamer" />


    <TextView
        android:id="@+id/nav_second_header_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/school"
        android:layout_marginEnd="15dp"
        android:layout_toStartOf="@+id/school"
        android:text="account name"
        android:layout_marginRight="15dp"
        android:layout_toLeftOf="@+id/school" />

</RelativeLayout>

这是onCreate MainActivity中的代码

        second_bar_header = findViewById(R.id.nav_second_header_bg); //this id returns null
        second_bar_header.setBackgroundColor(Color.parseColor("00ff00"));

        TextView tv = findViewById(R.id.nav_second_header_text); // this is null
        tv.setText("hi");

你应该尝试这样的事情

    NavigationView navigationView =  findViewById(R.id.you_nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    View header = navigationView.getHeaderView(0);

    TextView username =  header.findViewById(R.id.nav_second_header_text);
    username.setText("Hi");

    second_bar_header = header.findViewById(R.id.nav_second_header_bg); 
    second_bar_header.setBackgroundColor(Color.parseColor("00ff00"));

暂无
暂无

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

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