Search code examples
javaandroidandroid-activityfragmentandroid-framelayout

How I can use a Fragment without a id in android?


how can I find a fragment (framelayout) without id?

Here is my code:

private void setRect(int _x, int _y, int _w, int _h){

        final Rect rect = new Rect(_x,_y,_w,_h);

        final PSPDFConfiguration configuration = new PSPDFConfiguration.Builder(BuildConfig.PSPDFKIT_LICENSE_KEY)
                .scrollDirection(PageScrollDirection.HORIZONTAL)
                .build();

        final Uri  assetFile = Uri.parse("file:///android_asset/psp.pdf");

        final FrameLayout frameLayout = new FrameLayout(thisContext);

        runOnUiThread(new Thread(new Runnable() {
            @Override
            public void run() {

                frameLayout.setId(View.generateViewId());

                FrameLayout.LayoutParams params;

                params = new FrameLayout.LayoutParams(rect.right-rect.left,rect.bottom-rect.top);
                params.leftMargin = rect.left;
                params.topMargin = rect.top;
                params.gravity = 0;

                frameLayout.setLayoutParams(params);

                viewer_one.setLayoutParams(params);
                viewer_one.getSettings().setBuiltInZoomControls(true);
                viewer_one.setBackgroundColor(Color.BLUE);

                thisActivity.addContentView(viewer_one,params);

                PSPDFFragment fragment;

                FragmentManager manager = getSupportFragmentManager();

                fragment = (PSPDFFragment) manager.findFragmentById(frameLayout.getId());

                if(fragment == null){
                    fragment = PSPDFFragment.newInstance(assetFile,configuration);

                    getSupportFragmentManager()
                            .beginTransaction()
                            .replace(frameLayout.getId(), fragment)
                            .commit();
                }

            }
        }));


    }

I don't use a framelayout in my layout xml.

Update:

I have update my code and get this error -> No view found for id 0x1 (unknown) for fragment PSPDFFragment{373f9470


Solution

  • Set an ID to a view programatically

    Assign id via code (programmatically)

    Manually set ids using someView.setId(int); The int must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.) For example, if creating and numbering several views representing items, you could use their item number.

    This should do it. Now you have an ID, use it for the fragment manager. Hope this helps.