JRsz
JRsz

Reputation: 2941

Android: find a Button in a Dialog

I have a Dialog which is called by my MainActivity. Inside this Dialog lifes a custom Button. When I try to get that Button in my MainActivity with

Button createDateButton = (Button) findViewById(R.id.create_date_button);

it is always Null (therefore I get a Nullpointer exception later). I think is has something to do with the button beeing inside a Dialog...

The Dialog extends DialogFragment. It is called inside the MainActivity at runtime as a reaction to another Button. If there is more information you need, just tell me

Here is some more code:

MainActivity (partially, because it has 200+ lines)

public class MainActivity extends Activity implements UseDateInParentActivityInterface
{
    FragmentManager fragmentManager = getFragmentManager();

    CreateDialogFragment createDialogFragment;
    DialogFragment datePicker;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        homeFragment = new HomeFragment();

        fragmentManager.beginTransaction().add(R.id.mainFrame, homeFragment).commit();
        findViewById(R.id.bottomButton_home).setBackgroundResource(R.drawable.ic_home);
    }

    public void openCreate(View view)
    {
        createDialogFragment = new CreateDialogFragment();
        createDialogFragment.show(fragmentManager, "TEST");

        updateSelectedButton(3);
    }


    public void pickDate(View v)
    {
        datePicker = new DatePickerFragment();
        datePicker.show(getFragmentManager(), String.format(getResources().getString(R.string.pickDate)));
    }

    public void dateForWhatever(int year, int month, int day)
    {
        DateFormatter dateFormatter = new DateFormatter();
        String date = dateFormatter.toStringDE(year, month, day);

        Button createDateButton = (Button) findViewById(R.id.create_date_button);
        if (createDateButton != null)
        {
            createDateButton.setText(date);
        }
        else
        {
            System.out.println("bloeder Button ist gleich null");
        }
    }
}

This is the DialogFragment Java Class

public class CreateDialogFragment extends DialogFragment
{
    @Override
    public Dialog onCreateDialog(Bundle savedInstance)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater layoutInflater = getActivity().getLayoutInflater();

        builder.setView(layoutInflater.inflate(R.layout.dialog_create, null))
                .setMessage(R.string.create)
                .setPositiveButton(R.string.create, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i)
                    {}
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i)
                    {}
                });

        return builder.create();
    }
}

The Dialog xml.File

<?xml version="1.0" encoding = "utf-8"?>
<RelativeLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:tools = "http://schemas.android.com/tools"
    android:id = "@+id/dialog_create"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:background="@color/create_bg_1"
    tools:context = ".CreateDialogFragment"
    >

    <Button
        android:layout_width = "wrap_content"
        android:layout_height = "@dimen/textFieldHight"
        android:ems = "6"
        android:text = "@string/date"
        android:background="@color/white"
        android:id = "@+id/create_date_button"
        android:onClick = "pickDate"
        android:layout_below = "@id/dialog_create_name"
        />


</RelativeLayout>

John

Upvotes: 1

Views: 1877

Answers (2)

Gil Vegliach
Gil Vegliach

Reputation: 3562

In your CreateDialogFragment, modify your onCreateDialog():

@Override
public Dialog onCreateDialog(Bundle savedInstance)
{
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater layoutInflater = getActivity().getLayoutInflater();
    View root = layoutInflater.inflate(R.layout.dialog_create, null);

    builder.setView(root).setMessage(R.string.create);
    // ...

    Button createDateBtn = (Button) root.findViewById(R.id.create_date_button);
    // set click listener here ...

    return builder.create();
 }

The problem is that the button is in the view hierarchy of the Dialog, not the Activity's. If you call findViewById() from your Activity you'll always get null indeed: the hierarchies live in two different windows.

This snippet gets a handle of the button in the dialog. It calls findViewById() from the root view of your dialog (not the Activity) and retrieves the button. Then you can save it to a reference for later use or directly set a click listener there. In this listener you can write your own logic, for example call a method of your activity.

Upvotes: 1

Vlad
Vlad

Reputation: 910

Try this: Button createDateButton = (Button) rootView.findViewById(R.id.create_date_button);

This should be working.

Upvotes: 0

Related Questions