2016-05-22 65 views
1

我是新來的android開發,我試過搜索谷歌和stackoverflow周圍,但沒有發現任何問題或解決方案。如何以編程方式更改NavigationView標題背景?

我想以編程方式更改NavigationView標題背景,但得到了我不想要的東西。

這是MainActivity我試圖改變導航標題背景是這樣的:

View header = navigationView.getHeaderView(0); 
      tv_nav_header = (TextView)header.findViewById(R.id.text_nav_header); 
      tv_nav_header.setText(username); 
      tv_nav_header.setBackground(drawable); 

這是我nav_header.xml

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="match_parent" 
     android:layout_height="160dp"> 
     <cn.xyz.util.CircleImageView 
      android:layout_width="50dp" 
      android:layout_height="50dp" 
      android:layout_marginTop="40dp" 
      android:layout_marginStart="10dp" 
      android:src="@mipmap/ic_launcher" /> 

     <TextView 
      android:id="@+id/text_nav_header" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="55dp" 
      android:layout_marginStart="70dp" 
      android:text="tempLocalUser" 
      android:textColor="#FFFFFF" 
      android:background="@android:color/transparent"/> 
    </RelativeLayout> 

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?> 
    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:app="http://schemas.android.com/apk/res-auto" 
     android:id="@+id/drawer_layout" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:fitsSystemWindows="true"> 
       <FrameLayout 
        android:id="@+id/content" 
        android:layout_width="match_parent" 
        android:layout_height="0dp" 
        android:layout_weight="100" /> 
     <android.support.design.widget.NavigationView 
      android:id="@+id/navigation" 
      android:layout_width="wrap_content" 
      android:layout_height="match_parent" 
      android:layout_gravity="start" 
      app:headerLayout="@layout/nav_header" 
      app:menu="@menu/nav_drawer" /> 
    </android.support.v4.widget.DrawerLayout> 

實際像這樣展示,這不是我想要的 enter image description here

以下是我想要的,這是由nav_header.xml RelativeLayout的ATTR

的Android imple:背景= 「@顏色/ colorPrimary_blue」

enter image description here

對不起,我英文不好。

回答

0

您正在爲TextView設置背景顏色。請嘗試在RelativeLayout上設置顏色。請嘗試以下內容 -

View header = navigationView.getHeaderView(0); 
header.setBackground(drawable); 
tv_nav_header = (TextView)header.findViewById(R.id.text_nav_header); 
tv_nav_header.setText(username); 
tv_nav_header.setBackground(drawable); 
+0

是的,您是對的,謝謝! – feiffy

+0

請立即投訴並接受答案:) – jaibatrik

相關問題