Please have a look at this simple code – inside the switch I can’t use clear.getId(); no matter where I declare the clear button. In my posted code its been declared in onCreate. I know I can write/hardcode the id and it will be ok, but I want to code this the right way.
Code:
public class AddProduct extends Activity implements OnClickListener {
Button sendInfo, clear, cancel;
EditText name, quantity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
initializeVars();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
// *** --> case (clear.getid()) : break; // *** This doesnt work
// case R.id.bClear : break;
}
}
public void initializeVars() {
sendInfo = (Button) findViewById(R.id.bAddProduct);
clear = (Button) findViewById(R.id.bClear);
cancel = (Button) findViewById(R.id.bCancel);
name = (EditText) findViewById(R.id.etName);
quantity = (EditText) findViewById(R.id.etEnterQuantity);
sendInfo.setOnClickListener(this);
clear.setOnClickListener(this);
cancel.setOnClickListener(this);
}
}
Thanks
This is a bit messy, but you could extend each of the View classes and add a public int field. Initialise the field in the View’s constructor.
Then