How can I fire Onclick event programmatically?

Zakaria picture Zakaria · Jun 5, 2012 · Viewed 50.6k times · Source

I have a custom view with 2 linear layouts: the first is the view's header and the second is the the details view.

In the custom view, the OnClickListener of the header Linearlayout is already defined: when it fires, it collapses/expandes the second linearlayout.

What I want to do is to add more functionalities to my header's OnClickListener event (i.e.: collapse/expand the second layout and show a Toast).

I can't modify the source code of the custom view. I tried to set a new OnClickListener but it hides the initial event (collapse/expand).

How should I implement this?

The source code of My Custom View:

public class ExpandoLayout extends ViewGroup
{
    /* some declarations */
    private Linearlayout header;
    private linearlayout footer;

    /* some code */
    @override
    protected void onFinishInflate() {
    header= new LinearLayout(context);
    header.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleExpand();
            }
        });
    }
}

What I want to do is to add some code to the already defined OnClickListener event in my activity. Something like that:

public class myActivity extends Activity {
private Linearlayout myCustomView;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.rsdetail);
    myCustomView= (MyCustomView) findViewById(R.id.expanded);

    myCustomView.getChildAt(0).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if(v instanceof LinearLayout)
            {
                v.performClick();

                Toast.makeText(getActivity(), "ExpandoOnClickListener", 2000).show();
            }
        }
    });
}

Answer

waqaslam picture waqaslam · Jun 5, 2012

You can programmatically raise click event on a View to call it's OnClickListener as below:

view.performClick();

Now if you call this on your second layout under first layout's OnClickListener then i hope it should do the magic