Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a DialogFragment from within a CustomView

I'm working on one of my Android projects, trying to lessen the code inside my Activities. In one of them, I have CustomView (which just extends LinearLayout) that opens a DialogFrament when clicked. Now, the way I implement this is by overriding onTouch() in the activity and subsequently opening the DialogFrament from there. It looks something like this:

@Override
public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_UP) {
        if (v.getId() == mCustomView.Id()) {
            mDialogFragment.show(mFragmentManager, "");

I'd like to move the process of opening the DialogFragment away from the activity and into the CustomView itself, but, the problem I have is that I can't get an instance of FragmentManager (by using getSupportFragmentManager()) in the CustomView. Is what I'm planning possible, or should I stick to the code that I have working? I'm doing this so my code looks cleaner and easier to understand.

like image 617
user1923613 Avatar asked Aug 05 '13 15:08

user1923613


1 Answers

in your custom view you can call getContext() (which will be your activity) so then you can cast it to android.support.v4.app.FragmentActivity and call getSupportFragmentManager() from there.

So this should do it.

android.support.v4.app.FragmentActivity fragmentActivity = (android.support.v4.app.FragmentActivity) getContext();
FragmentManager fm = fragmentActivity.getSupportFragmentManager();
like image 99
petey Avatar answered Oct 05 '22 23:10

petey