There is 1 activity, in it 2 buttons, 1 TextView, 2 string resources. When you press the button 1, the text from it (the string resource of the button 1) gets and is set to TextView; when you press the button 2, everything is the same (only the string resource is different). For simplicity, while divided into two buttons. In the future, the button will be one; after clicking, it will change its string text resource and, depending on the resource, it will be installed in texView.
View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { Button btn = (Button)v; String btnText = btn.getText().toString(); if (btnText.equals("Left")) { tv.setText(R.string.btn_left); } else if (btnText.equals("Right")) { tv.setText(R.string.btn_right); } else { Toast toast = Toast.makeText(MainActivity.this, "Wrong", Toast.LENGTH_SHORT); toast.show(); } } }; Tried to get through getResources (). GetString (), but something did not work. While the text in .equals () is set hard, because Pushing there R.string.btn_left / right does not work.
I did it and it worked:
public class MainActivity extends Activity implements View.OnClickListener { Button btn_left; Button btn_right; TextView tv; String leftStr; String rightStr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.textView); btn_left = (Button) findViewById(R.id.button); btn_left.setOnClickListener(this); btn_right = (Button) findViewById(R.id.button2); btn_right.setOnClickListener(this); leftStr = getString(R.string.btn_left); rightStr = getString(R.string.btn_right); } @Override public void onClick(View v) { Button btn = (Button)v; String btnText = btn.getText().toString(); if (btnText.equals(leftStr)) { tv.setText(R.string.btn_left); } else if (btnText.equals(rightStr)) { tv.setText(R.string.btn_right); } else { Toast toast = Toast.makeText(MainActivity.this, "Wrong 1", Toast.LENGTH_SHORT); toast.show(); } } } Any comments on this code?
getString(R.string.app_name)But it is not entirely clear what exactly does not work for you? - Android Android