1

I have a fragment SelectFileFragment that has a innerclassTest. I need to use the context i.e. the activity that started the fragment SelectFileFragment in its innerclassTest.

I'm new to Kotlin so I want to know how I can get the context and then use in the inner class.

//there will be a few lines of code in java representing what i'm trying to achieve.

class FileSelectFragment : BaseFragment() {

public Context context;      //java


override fun onCreateView{
....
context = getActivity();   //java
....

}
class Test(){

private fun testMethod(){

context.getString(...);    //java

}

}

}

2 Answers 2

4

In Kotlin, a class must be explicitly declared inner class in order to use fields / methods from the outer class.

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

5 Comments

Alright. But how do I get context in the first place in Kotlin?
And saving it in a variable.
context is already a property made available to you (Kotlin rewrites getContext() as context), so you don't need to save it as a variable or do anything. You'll probably want to use requireContext() though if you want a non-null Context instance.
Now, I'm getting this error: Constructor of inner class can be called only with receiver of containing class
You can't create an inner class from outside of the outer class. That's true for both Kotlin and Java.
3

Adding this answer to make it clear for you. The answer is same as what @ianhanniballake posted above.

Please find the complete code snippet below : If you this this answers your question, please mark @ianhanniballake post as the answer.

class FileSelectFragment : BaseFragment() {

inner class Test(){

    private fun testMethod(){
        context.getString(R.string.app_name);    //java
    }
}

}

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.