I've just started out with android (and java, yes I am learning the two simultaneously). As a basic project to develop skills I've been trying to write code for a calculator.
The keypad is formed of buttons, I have opted to put text on these through use of strings (I have read this is good practice to use strings over hard coded text). Then, when the buttons are 'clicked' they append/setText of a TypeView item (as a calculator should!)
The use of strings is causing me problems.
If I had hard coded the text on buttons, I could use this:
//this part for initial reading as 0 and for disp usage later
TextView disp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
disp=(TextView)findViewById(R.id.textView);
disp.setText("0");
}
public boolean onCreateOptionsMenu(Menu menu) {}
static boolean isempty=(true);
public void onClick(View btn)
{
Button bt = (Button)btn;
if (disp.getText().length()>7) return;
if (isempty)
{
disp.setText(bt.getText());
isempty=false;
}
else
{
disp.append(bt.getText());
}
}
in order to write the text to screen.
Yes, it has much work, I know. Please could someone shed light on how to append/setText from strings? (ie how to modify the disp.append/disp.setText parts
Thanks in advance!!!
You need to create a file called string.xml in res/values.
The file should have the following format:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello!</string>
</resources>
Now to access that string, on your code you do:
String string = getString(R.string.hello);
Now you can set that string to your buttons.
Next, in your code you have to set the click listener to the buttons in your calculator, the TextView shouldn't be handling any events in this case. Your event for each button would be declared like this:
btn01.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Button btn = (Button) v;
disp.append(btn.getText());
}
});
On your operator buttons for adding, substracting, etc. you need the event listeners to look like this:
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// handle the adding
}
});