0

I'm trying to create a LinearLayout in another activity called MainFragment. Inside onCreate function I'm using the line

LinearLayout parent = new LinearLayout(MainFragment.this);

using this shows same error

error:

LinearLayout (andorid.content.Context) in LinearLayout cannot be applied to (com.example.name.nav_bar.MainFragment)

If I try the code in MainActivity it works fine.

2
  • LinearLayout constructor needs a Context, while a Fragment is not a subclass of Context, and Activity is a subclass of Context. Commented Nov 1, 2018 at 15:11
  • You can use either one -- LinearLayout parent = new LinearLayout(getContext); LinearLayout parent = new LinearLayout(getActivity); Commented Nov 1, 2018 at 15:21

1 Answer 1

2

Try this instead:

LinearLayout parent = new LinearLayout(getActivity());

When working with Fragments for the first time, it's important to understand how they are different from Activities. One of these ways is that an Activity is an Android Context, but a Fragment is not. Many things depend on having a Context to work with, so if you're inside a Fragment you need some way to get access to a Context. The easiest way is often to call getActivity() (since, again, an Activity is a Context).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.