I am learning how to use fragments, and in my MainActivity.java I have this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
A a = new A();
B b = new B(a);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new ContentFragment())
.commit();
ContentFragment frag = (ContentFragment) getSupportFragmentManager()
.findFragmentById(R.id.container);
frag.doInject(b);
}
}
If I try to inject the dependency directly into the constructor of the fragment, Android Studio barks at me. So I'm trying this approach, but when debugging I get to where I am setting frag, and it's just null and is always null. So, I guess what I need to know is, in the simplest way possible, how do I call my doInject(b) and inject b into my fragment?
Another thing too, which I'm not sure about, is that later if I have a listener in the same MainActivity.java file, and I want to update the fragment with new content, I was hoping to do something like this:
@Override
public void handleResponseData(String s) {
frag.updateTextbox(s);
}
But I have a feeling that I'm going to run into problems with that too. So I need some help understanding what it is that I'm trying to do. I've spent at least 5 hours trying to figure this out, and need some help, please!
Edit to show layout files:
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" />
fragment_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=".MainActivity">
<TextView
android:id="@+id/textbox"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World" />
</FrameLayout>