Ahzam Ahmad
Ahzam Ahmad

Reputation: 35

Placing Camera2 into a fragment

I wish to use the camera2 package to include a camera within my app. The problem arises when I have to fit it into a fragment. I have three fragments within a viewpager that can be swiped through. I want the last fragment to be a camera app that is always on (only when the app is open of course) similar to that of snapchat. How would I go around implementing this. I've managed to get camera2 to work standalone but not within a fragment. Thanks

Main Activity:

public class MainActivity extends FragmentActivity {
    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mViewPager = (ViewPager) findViewById(R.id.pager);
        PagerAdapter pAdapter = new PagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(pAdapter);
        setCurrentItem(1, false);
    }

    // This method is called ChatFragment.java and uses viewPager to smoothScroll to the desired fragment
    public void setCurrentItem (int item, boolean smoothScroll) {
        mViewPager.setCurrentItem(item, smoothScroll);
    }
}

PagerAdapter:

public class PagerAdapter extends FragmentPagerAdapter {

    public PagerAdapter(FragmentManager fm) {
        super(fm);

    }
    @Override
    public Fragment getItem(int arg0) {
        switch (arg0) {
            case 0:
                return new MessageFragment();
            case 1:
                return new ChatFragment();
            case 2:
                return new CameraFragment();
            default:
                break;
        }
        return null;
    }
    @Override
    public int getCount() {
        return 3;
    }
}

Camera Fragment:

public class CameraFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.camera_fragment_layout, container, false);
    }
}

Upvotes: 1

Views: 1444

Answers (1)

Mick
Mick

Reputation: 25481

The Google Camera2Basic example uses a Fragment so it would be a good starting point: https://github.com/googlesamples/android-Camera2Basic

Take a look at the issues log and recent Camera2 tagged questions also as there are some known issues which it is worth learning about the easy way first.

Upvotes: 1

Related Questions