Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding TextView Programmatically in Fragment and setting to mainLayout

In my Fragment, instead of returning a view of my correspoding XML file, I am creating a layout and adding view to it as follows and then returning that layout:

LinearLayout firstLinearLayout = new LinearLayout(getActivity());
LinearLayout secondLinearLayout = new LinearLayout(getActivity());

LinearLayout mainLayout = new LinearLayout(getActivity());
    mainLayout.setBackgroundColor(Color.TRANSPARENT);
    mainLayout.setOrientation(LinearLayout.VERTICAL);
    mainLayout.addView(firstLinearLayout);
    mainLayout.addView(secondLinearLayout);

return(mainLayout);

Now, I've also tried to create a rootView to inflate my xml, and then access a TextView in that xml as follows:

View rootView = inflater.inflate(R.layout.xml_layout, container, false);

TextView check = (TextView) rootView.findViewById(R.id.textView);

and then add this TextView to my mainLayout:

mainLayout.setBackgroundColor(Color.TRANSPARENT);
mainLayout.setOrientation(LinearLayout.VERTICAL);
mainLayout.addView(firstLinearLayout);
mainLayout.addView(secondLinearLayout);
mainLayout.addView(check);

However, in the line assigning the TextView from my XML to check, I get a NullPointerException. I can't figure out why, can anyone help me out? Thank you.

Edit - Here is my XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@color/transparent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="here is random text"
    android:textColor="@color/white"
    android:gravity="center"
    android:textStyle="bold"
    android:textSize="30sp"
    android:id="@+id/mphTextView" />

</RelativeLayout>
like image 278
AreM Avatar asked Dec 14 '25 17:12

AreM


1 Answers

You should be using

check = (TextView) rootView.findViewById(R.id.mphTextView);

if the layout you have provided is the layout that you have inflated with rootView

like image 195
ginsengtang Avatar answered Dec 16 '25 08:12

ginsengtang