![](/img/trans.png)
[英]Is it possible to setText of TextView in MainActivity.java using string.xml?
[英]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.