How to pass parameters to OnClickListener?

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

    Another solution may be to not write the code directly inside onClick() method, alternatively, write the code in a separate method, and then call that method in onClick().

    Example:

    button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
        function();
       }
    });
    
    private void function() {
     //your code here
    }
    
    0 讨论(0)
  • 2020-11-29 21:46

    Note that you do this in Kotlin a little differently from how you do it in Java. In Kotlin, you append NameOfParentClass() to the subclass declaration.

    Now override Activity‘s onCreate() method. It will look something like this.

    class MainActivity : AppCompatActivity() {
            private var btnClick: Button? = null
            override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
                setContentView(R.layout.activity_main)
                btnClick = findViewById(R.id.btnClick) as Button
                btnClick!!.setOnClickListener { startActivity(Intent(this@MainActivity, KotlinActivity::class.java)) }
            }
        }
    
    0 讨论(0)
  • 2020-11-29 21:47
    1. Have your activity implement View.OnClickListener
    2. Register your buttons to the listener
    3. Check which button is clicked in onClick
    4. Process your string depending on which button was clicked

      public class _Test2Activity extends Activity implements OnClickListener {
      
         private Button button1;
         private Button button2;
         private Button button3;
      
         private String myString;
      
         @Override
         public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.main);
      
           button1 = (Button)findViewById(R.id.button1);
           button2 = (Button)findViewById(R.id.button2);
           button3 = (Button)findViewById(R.id.button3);
      
           button1.setOnClickListener(this);
           button2.setOnClickListener(this);
           button3.setOnClickListener(this);   
      
           myString = "This is a string";
      
         } 
      
         @Override
         public void onClick(View v) {
             if(v==button1) {
                //do something with myString
             } else if(v==button2) {
                //do something with myString
             } else if (v==button3) {
                //do something with myString
             }
         }
      }
      
    0 讨论(0)
提交回复
热议问题