Home > Software design >  Fragment cannot be converted to Fragment nextFragment
Fragment cannot be converted to Fragment nextFragment

Time:10-01

I am very new to android/java dev so bear with me a bit here.

I am using

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

and a button to load a

case R.id.btn_test:
nextFragment = new TestFragment();
break;

Then on TestFragment.java I have

public class TestFragment extends Fragment {

private View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_test, container, false);

    return view;
}

So when the button btn_test is pressed, it goes to TestFragment.java, which then loads the fragment_test.xml layout - as far as I can tell.

However, I want my TestFragment to (as an example) load a video. So I change it to something like this

public class TestFragment extends AppCompatActivity  {

    private WebView webView;
    String youTubeUrl = "https://www.youtube.com/embed/47yJ2XCRLZs";

    String frameVideo = "<html><body>Video From YouTube<br><iframe width=\"420\" height=\"315\" "  
            "src='"   youTubeUrl   "' frameborder=\"0\" allowfullscreen>"  
            "</iframe></body></html>";


    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.webView);
.. etc

But now I get error: incompatible types: TestFragment cannot be converted to Fragment nextFragment = new TestFragment(); I assume this is because my new TestFragment extends AppCompatActivity instead of TestFragment extends Fragment.

I have tried something along the lines of

public class TestFragment extends AppCompatActivity, Fragment {

But I don't think that is possible. ANy ideas how I can get my new java to load?

CodePudding user response:

I suspect you have the wrong idea about fragments, what they're and how to correctly start & navigate between them, what gave me this idea is that you shouldn't be initializing a fragment like that rather you should use navigation component to navigate between them, (A fragment is not a java class to do your work, it should handle a view that displays UI to the user during their Lifecycle), with that being said I'm recommending that you start reading about them in the android developers tutorial to gain more information on how to deal with.

tutorial image

you could also take the navigation component lab on Android Developers site which I highly recommend where it should instruct you how to setup your project with it.

Learn Jetpack Navigation | Android Developers

  • Related