Reputation: 3541
How can I handle an OnClick method in a fragment without making a ton of onclick listeners for each button and then having a huge switch statement for them. For example, I have 10 checkboxes in my layout and I want the fragment to handle them all in the same way (have the same OnClick)
Upvotes: 1
Views: 53
Reputation: 2264
First of all, your question is ambigue. It is not 100% clear what you want to know.
If I understand correctly you do not want 10 seperate listeners, but only 1.
Then you get:
public class Main2Activity extends AppCompatActivity implements View.OnClickListener{
private Button button01;
private Button button02;
private Button button03;
private Button button04;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
button01 = (Button) findViewById(R.id.button01);
button02 = (Button) findViewById(R.id.button02);
button03 = (Button) findViewById(R.id.button03);
button04 = (Button) findViewById(R.id.button04);
button01.setOnClickListener(this);
button02.setOnClickListener(this);
button03.setOnClickListener(this);
button04.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view == button01) {
// button01 clicked
} else if (view == button02) {
// button02 clicked
} else if (view == button03) {
// button03 clicked
} else if (view == button04) {
// button4 clicked
}
}
}
Is this what you were looking for?
Upvotes: 0
Reputation: 3029
Its pretty easy. Just do it like this if you want to handle them same way;
View.OnClickListener listener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(MainActivity.this,"asdasd",Toast.LENGTH_SHORT).show();
}
};
item1.setOnClickListener(listener);
item2.setOnClickListener(listener);
item3.setOnClickListener(listener);
Upvotes: 1