How to pass parameters to OnClickListener?

后端 未结 9 2247
南旧
南旧 2020-11-29 20:59

How can i pass parameter to an OnClickListener() ?

Got my Listener:

   OnClickListener myListener = new OnClickListener()
   {

     @Override
     p         


        
9条回答
  •  眼角桃花
    2020-11-29 21:35

    If you have static content associated with the view, another option is to use a HashMap to map the view id to the content.

    private static Map idToStringMap = new HashMap();
    

    Initialize the map in onCreate:

    idToStringMap.put(R.id.button1, "hello");
    idToStringMap.put(R.id.button2, "world");
    // ...
    

    Then get the value from the view id in onClick:

    public void onClick(View v) {
    
        String myString = idToStringMap.get(v.getId());
    }
    

    This is a little cleaner than using a long set of switch cases.

提交回复
热议问题