0

I was able to access the hardcoded pre-instantiated fragment but the cast fails. Trying to call setArguments or call specific methods on the class.

to be able to call Fragment.setArguments on findViewById(R.id.product); can solve my problem though

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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">

    <fragment
        android:id="@+id/product"
        android:name="Product"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/product_fragment" />

</android.support.constraint.ConstraintLayout>

MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(savedInstanceState == null) {
            findViewById(R.id.product); // works
            findViewById(R.id.product).findViewById(R.id.subview); // works
            Product frag = (Product) findViewById(R.id.product); // cast fails
        }
    }
}

Product

public class Product extends Fragment {
    // implementation
}
AppDeveloper
  • 1,816
  • 7
  • 24
  • 49

1 Answers1

1

findViewById() returns View only.

You may use

getSupportFragmentManager().findFragmentById(R.id.yourFragmentId)

refer to this post.

https://stackoverflow.com/a/23592993/6854435

EDIT:

After some research, seems you can't call setArguments before the fragment is attached using your method.

  • However, you can do setArgumentsif you add your fragment programmatically:

How do I add a Fragment to an Activity with a programmatically created content view

Community
  • 1
  • 1
EricHo
  • 183
  • 10
  • Thanks, then how would I access the arguments passed by `setArguments` method in a post creation scenario? – AppDeveloper Oct 24 '19 at 10:50
  • shall I create a custom method on Fragment class and call it separately while passing the data? – AppDeveloper Oct 24 '19 at 11:08
  • I think If you are using the data after the fragment is attached, you may set up your custom method -- https://stackoverflow.com/questions/13034746/if-i-declare-a-fragment-in-an-xml-layout-how-do-i-pass-it-a-bundle – EricHo Oct 25 '19 at 01:54