I've looked on SO for a solution to this and I can't find one that works for my situation. I'm a beginner with Android development, so let me know if I'm doing something obviously wrong.
First a little background on the structure of my app. I use a navigation drawer with fragments for each of the pages, similar to the navigation drawer example in the Android documentation. On one of the pages I want to dynamically add TextViews to the LinearLayout of the fragment for that page when some event happens. The event isn't important in this case - it just calls a method in my activity.
So in my activity I have a method - addText(). Whenever addText() is called, I want to create a TextView, and then add this to the LinearLayout in the fragment. (the LinearLayout with id diary_layout)
How do I do this?
I have tried the following method. When this method is called, I do not see the text in the page.
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);
}
This is the structure of the layout file for the fragment:
<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>
Activity Layout:
<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"/>
Thanks in advance!