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);
}
}
@Override
public void handleResponseData(String s) {
frag.updateTextbox(s);
}
<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" />
<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>
If I try to inject the dependency directly into the constructor of the fragment
I'm not sure about that doInject
method, but you should read Best practice for instantiating a new Android Fragment
For example,
ContentFragment frag = ContentFragment.newInstance(b);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, frag, "TAG")
.commit();
// frag.doInject(b); // Can do, but not necessary
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
Generally, this is not how you do that.
frag.updateTextbox(s);
I assume you have the Activity attached to the Fragment via a listener with a handleResponseData(String s)
, and you'd have to do
String s = "foo";
if (listener != null) {
listener.handleResponseData(s);
}
therefore, instead of that, you only need do this
String s = "foo";
updateTextbox(s);
/*
if (listener != null) {
listener.handleResponseData(s);
}
*/