How can I implement the switch in Google translator or in the screenshot below? enter image description here

I did it, but the texts are switched from the second click on the button.

public class MainActivity extends AppCompatActivity { private int sw; TextView txtLeft; TextView txtRight; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtLeft = findViewById(R.id.txtLeft); txtRight = findViewById(R.id.txtRight); ImageButton btnRef = findViewById(R.id.btnRef); sw = 0; txtLeft.setText("Русский"); txtRight.setText("Английский"); btnRef.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (sw){ case 0: txtLeft.setText("Русский"); txtRight.setText("Английский"); sw = 1; break; case 1: txtLeft.setText("Английский"); txtRight.setText("Русский"); sw = 0; break; } } }); } } 
  • What exactly do you want to achieve? To change the text between the buttons, or to put the same button, or so that when pressed it turns over? - Valeriy
  • I want the texts to be switched by clicking on the button and depending on how they are switched to do actions. For example, if Russian is on the left, and English on the right is one action; - WAY
  • Maybe there is a better solution - WAY
  • The second time, and then everything is fine? Put sw = 1. I myself do not like such tasks, they are almost impossible to make neat and elegant. - Valeriy
  • Yes, then it switches normally. - WAY

1 answer 1

Shorter solution:

 public class MainActivity extends AppCompatActivity { private boolean isENGRight; TextView txtLeft; TextView txtRight; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtLeft = findViewById(R.id.txtLeft); txtRight = findViewById(R.id.txtRight); ImageButton btnRef = findViewById(R.id.btnRef); txtLeft.setText("Русский"); txtRight.setText("Английский"); btnRef.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { txtRight.setText(isENGRight? "Английский":"Русский"); txtLeft.setText(isENGRight? "Русский":"Английский"); isENGRight = !isENGRight; } }); } } 

Actions can be performed as isENGRight :

 if (isENGRight) { //ΠΏΠ΅Ρ€Π΅Π²ΠΎΠ΄ с русского Π½Π° английский } else { // ΠΏΠ΅Ρ€Π΅Π²ΠΎΠ΄ с английского Π½Π° русский } 
  • Thank you .. this decision is better - WAY