【发布时间】:2015-01-24 03:50:31
【问题描述】:
我已经在 SO 上寻找解决方案,但找不到适合我情况的解决方案。我是 Android 开发的初学者,所以如果我做错了什么,请告诉我。
首先介绍一下我的应用程序结构的背景知识。我为每个页面使用带有片段的导航抽屉,类似于 Android 文档中的导航抽屉示例。在其中一个页面上,当某些事件发生时,我想动态地将 TextViews 添加到该页面的片段的 LinearLayout 中。在这种情况下,事件并不重要 - 它只是在我的活动中调用一个方法。
所以在我的活动中,我有一个方法 - addText()。每当调用 addText() 时,我想创建一个 TextView,然后将其添加到片段中的 LinearLayout 中。 (id为diary_layout的LinearLayout)
我该怎么做?
我尝试了以下方法。调用此方法时,我看不到页面中的文字。
public void textAdd(){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.fragment_diary, null);
LinearLayout diaryLayout = (LinearLayout) contentView.findViewById(R.id.diary_layout);
TextView newTextView = new TextView(this);
newTextView.setText("Testing");
diaryLayout.addView(newTextView);
}
这是片段布局文件的结构:
<LinearLayout
android:id="@+id/theLinearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/diary_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MyActivity$PlaceholderFragment">
</LinearLayout>
</ScrollView>
活动布局:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!-- The navigation drawer -->
<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="10dp"
android:background="#FFFFFF"/>
提前致谢!
【问题讨论】:
-
您的
contentView未使用。发布您的活动布局。 -
我在方法的第三行使用它。 LinearLayout diaryLayout = (LinearLayout) contentView.findViewById(R.id.diary_layout);
-
您需要将 contentView 附加到片段或活动中。您的代码中没有任何内容正在执行此操作。
-
是的,您向其中插入了一个项目。但是您的
contentView在哪里。无处。它尚未添加到您的活动中。
标签: android android-layout android-fragments dynamic android-linearlayout