我制作了一个带有 3 个按钮的自定义导航抽屉,我想根据它们关联的活动更改按钮上的文本。因此,当我使用 LayoutInflater 制作导航抽屉布局的 Java 对象并使用该布局对象上的 findViewById 获取每个按钮的句柄时,我设置了每个按钮的文本,但是当我运行应用程序时,文本不会出现(在 XML 中我没有为按钮设置任何文本)。休息一切正常。
<FrameLayout 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/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sahil.childcare.NavigationalDrawerFragment">
<RelativeLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<include
layout="@layout/nav_profile"
android:id="@+id/nav_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/nav_profile"
android:layout_marginLeft="-5dip"
android:layout_marginRight="-5dip"
android:layout_marginTop="-5dip"
android:layout_marginBottom="-5dip"
android:id="@+id/top_button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/top_button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginLeft="-5dip"
android:layout_marginRight="-5dip"
android:layout_marginTop="-7dip"
android:layout_marginBottom="-5dip"
android:id="@+id/middle_button" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/middle_button"
android:id="@+id/bottom_button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginLeft="-5dip"
android:layout_marginRight="-5dip"
android:layout_marginTop="-7dip"
android:layout_marginBottom="-5dip"/>
</RelativeLayout>
</FrameLayout>
涉及此抽屉的主要活动(onCreate()方法内部)中的代码部分在这里
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_navigational_drawer,null);
Button topButton = (Button) view.findViewById(R.id.top_button);
Button middleButton = (Button) view.findViewById(R.id.middle_button);
Button bottomButton = (Button) view.findViewById(R.id.bottom_button);
topButton.setText("School");
topButton.setTextColor(getResources().getColor(R.color.red));
middleButton.setText("Teacher");
middleButton.setTextColor(getResources().getColor(R.color.red));
bottomButton.setText("Child");
bottomButton.setTextColor(getResources().getColor(R.color.red));