将TextView添加到导航抽屉模板中的content_main



当setContentView处于activity_main时,我正试图将TextView添加到content_main布局中。当您在Android Studio中创建新项目时,我目前正在使用导航抽屉模板。Activity_main包括app_bar_main,app_bar.main包括content_main。

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/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="org.test.testy.test"
tools:showIn="@layout/app_bar_main"
android:weightSum="1">
</LinearLayout>

尝试使用的代码是:

LayoutInflater inflater;
inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = (View) inflater.inflate(R.layout.content_main, null);
LinearLayout layout = (LinearLayout) view.findViewById(R.id.content_main);
//Card view create
CardView cv = new CardView(layout.getContext());
cv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
cv.setVisibility(View.VISIBLE);
TextView tv = new TextView(layout.getContext());
tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
tv.setText("Test");
tv.setVisibility(View.VISIBLE);
cv.addView(tv);
layout.addView(cv);

//卡视图创建下面的所有内容都在一个空白应用程序中进行了测试,效果非常好。我还尝试在content_main的xml中放入一个带有id的TextView,并尝试读取文本,这也返回了正确的文本。如果我能够访问布局,并且添加到视图的代码很好,那么为什么它不起作用呢?

我做错了两件事:

  1. 我必须用它要去的确切名称和来识别每个<include>

  2. 我必须检查每个包含项,因为我有两个:

    LinearLayout layout = (LinearLayout) findViewById(R.id.app_bar_main).findViewById(R.id.content_main);
    

最新更新