How to pass parameters to OnClickListener?

后端 未结 9 2259
南旧
南旧 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:27

    I know this is a late answer but hopefully it can help someone. None of the existing answers worked in my situation but I ended up using the setTag feature of an image that was acting like a button. My account info was in a global member variable that was set up when the activity started.

    In this case I am setting up a table with each row being an account. The account details are shown when the image is clicked (the image is just an info icon).
    Thus:

    // prior code....
    // NOTE: oneAccount is an object (AccountInfo) holding information about the account
    
    // column with the "detail" arrow
    image1 = new ImageView(this);
    image1.setImageResource(R.drawable.info);
    image1.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
    image1.setPadding(15, 1, 15, 1);
    image1.setTag(oneAccount);
    // add a listener to go to that account detail on a click
    image1.setOnClickListener(new TextView.OnClickListener() {
        public void onClick(View v) {
        // change the color to signify a click
        v.setBackgroundColor(getResources().getColor(R.color.button_selected));
    
    
        // get what we need out of the tag
        AccountInfo thisAcct = (AccountInfo) v.getTag();
    
            // your code would do other stuff here
    
    }
    });
    
    // add the image to the table row
    tr1.addView(image1);
    

提交回复
热议问题