Jasmine Jasmine - 5 months ago 11
Java Question

accessing a layout(.xml) from a java class in android studio

I have this layout (activity_main2.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"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="@+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</android.support.v4.widget.DrawerLayout>


as you see it is calling another layout (app_bar_main2.xml):

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main2" />
</android.support.design.widget.CoordinatorLayout>


and this one is calling another layout (content_main2.xml):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dear user!"
android:id="@+id/txtUserName_Main"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>


I have a java class (Welcome.Java) which calls "activity_main2.xml" in "onCreate" by the following code:

setContentView(R.layout.activity_main2);


Now I want to access the TextView , in content_main2.xml from the Welcome.Java , and set the text of TextView to the real username which I have read from database.
would you please guide me how to point to the TextView and set its value?

Thanks!

Answer

You just need to do:

TextView userName = (TextView) findViewById(R.id.txtUserName_Main);
userName.setText("YOUR_USERNAME");
Comments