简体   繁体   中英

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>

there is no need of LayoutInflater. Simply use:

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

Hope this helps.

You just need to access the TextView component the normal way. With that template the content_main.xml is included inside the main layout, so you sould do as follows in your main activity (maybe inside the onCreate method or wherever you need):

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

    //...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView txt = (TextView)view.findViewById(R.id.txt_head);
        txt.setText("sdfsdf");
    }

    //...
}

Assuming that you have a app_bar_main.xml inside the main layout wich contains the content_main.xml. In the end everything is accessible from the main activity directly since the layouts are included in the main layout.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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