Waterfront Waterfront - 2 months ago 8
Android Question

Change TextView on content_main.xml in MainActivity.java

I'm using the Android Studio standard template "Navigation Drawer Activity" which contains the content_main.xml layout.

On this layout is my textView which I want to change the text from my MainActivity.java.

I tried following but nothing changes:

LayoutInflater inflater = (LayoutInflater)this.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.content_main, null);
TextView txt = (TextView)view.findViewById(R.id.txt_head);
txt.setText("sdfsdf");


content_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/relativelayout_for_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.w4ter.ledcontroldesign.MainActivity"
tools:showIn="@layout/app_bar_main"
android:orientation="vertical"
android:paddingTop="10dp">

<TextView
android:text="Presets"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.AppCompat.Headline"
android:id="@+id/txt_head" />

<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#61000000" />
</LinearLayout>

Answer

there is no need of LayoutInflater. Simply use:

TextView textView = (TextView) findViewById(R.id.txt_head);
texView.setText("Hello");

Hope this helps.