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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With