How can i pass parameter to an OnClickListener() ?
Got my Listener:
OnClickListener myListener = new OnClickListener()
{
@Override
p
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
}
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)) }
}
}
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
}
}
}