我之前已经问过这个问题,但到目前为止提供的解决方案对我没有帮助。
我有一个基本的布局:
activity_main.xml中
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="@+id/my_toolbar"
layout="@layout/test_toolbar"/>
<android.support.design.widget.TabLayout
android:id="@+id/maths_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/maths_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
包含布局:
test_toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello workd"
android:textSize="20sp" />
</android.support.v7.widget.Toolbar>
我想在include布局中找到TextView。
代码我到目前为止已经尝试但没有奏效:
Toolbar toolbar= findViewById(R.id.test_toolbar);
TextView toolbarTitle= toolbar.findViewById(R.id.tv_title);
toolbarTitle.setTextColor(getResources().getColor(R.color.red));
如何在包含布局中找到视图?
答案 0 :(得分:0)
非常简单的错误:
在您的代码中,您使用错误的ID执行findViewById
。 id必须是包含布局的id。
改变这个:
Toolbar toolbar = findViewById(R.id.test_toolbar);
对此:
Toolbar toolbar = findViewById(R.id.my_toolbar);