Search code examples
javaandroidandroid-custom-view

Setting listener to custom view


I have a view which dynamically add a custom view made with a checkbox, an edittextand a imagebutton. I want to add listeners to the imagebuttonto delete the custom view(or set the visibility to gone if the imagebuttonis pressed. This is my code so far, starting with the more basic stuff:

 public void addView() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View view = inflater.inflate(R.layout.item_task_list, null);
        ImageButton img_btn = findViewById(R.id.delete);
        EditText name_et = findViewById(R.id.todo);
        CheckBox done_cb = findViewById(R.id.done);
        img_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 // Do something
            }
        });
        parentLayout.addView(view, parentLayout.getChildCount() - 1);

This works as long as I don't have the listener. With it, I get this error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

It works if I set the listener like this: img_btn.setOnClickListener(this); and then use the OnClickmethod from the activity. There I have:

case R.id.delete:
        v.getParent().
        break;

But then I can't set the visibility to gone nor remove it.

This is my first time adding custom views, so I'm not sure what I'm missing, if I should make a class, set the listener from other way, or how to access it.


Solution

  • try to call findViewById from inflated view. It should help.

    public void addView() {
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View view = inflater.inflate(R.layout.item_task_list, null);
            ImageButton img_btn = view.findViewById(R.id.delete);
            EditText name_et = view.findViewById(R.id.todo);
            CheckBox done_cb = view.findViewById(R.id.done);
            img_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                     // Do something
                }
            });
            parentLayout.addView(view, parentLayout.getChildCount() - 1);