簡體   English   中英

在 MainActivity.java 中更改 content_main.xml 上的 TextView

[英]Change TextView on content_main.xml in MainActivity.java

我正在使用包含 content_main.xml 布局的 Android Studio 標准模板“導航抽屜活動”。

在這個布局上是我的 textView,我想從 MainActivity.java 更改文本。

我嘗試了以下但沒有任何變化:

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>

不需要 LayoutInflater。 只需使用:

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

希望這可以幫助。

您只需要以正常方式訪問 TextView 組件。 使用該模板, content_main.xml 包含在主布局中,因此您應該在主活動中執行以下操作(可能在 onCreate 方法中或您需要的任何地方):

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");
    }

    //...
}

假設您在包含 content_main.xml 的主布局中有一個 app_bar_main.xml。 最后,所有內容都可以直接從主活動訪問,因為布局包含在主布局中。

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM