从另一个布局设置文本视图

时间:2018-02-23 02:05:15

标签: java android android-activity layout textview

所以我的活动看起来像这样: home.java

在导航视图中有一个textview,假设在用户登录时显示用户名。但我不知道该怎么做...

这是我使用的xml( activity_home.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.epizy.someone.tetrisunda.home">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar">
            <ImageButton
                android:layout_marginRight="10dp"
                android:background="?attr/selectableItemBackground"
                android:layout_gravity="right"
                android:src="@drawable/ic_refresh"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </android.support.v7.widget.Toolbar>
    <include layout="@layout/content_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/toolbar"/>
</RelativeLayout>

<android.support.design.widget.NavigationView
    app:headerLayout="@layout/nav_header"
    app:menu="@menu/menu_home"
    android:fitsSystemWindows="true"
    android:layout_gravity="start"
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"/>

textview位于名为 nav_header 的xml文件中,有点像这样:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:padding="10dp"
  android:background="#eeeeeeee"
  android:layout_width="match_parent"
  android:layout_height="192dp">
<TextView
    android:id="@+id/menu_home_username"
    android:layout_gravity="bottom"
    android:textColor="@color/colorPrimary"
    android:text="USERNAME"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
 </FrameLayout>

如何使用 home.java 更改nav_header中的文字?

2 个答案:

答案 0 :(得分:0)

请运行这些行。

TextView menu_home_username= (TextView)findViewById(R.id.menu_home_username);
menu_home_username.setText("SomeText");

答案 1 :(得分:0)

您可以从Home.java中更改nav_header中的文本 -

NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view);
View header = navigationView.getHeaderView(0);
menu_home_username = (TextView)header.findViewById(R.id.menu_home_username);
menu_home_username.setText("set any text here");
相关问题