I have 4 buttons and 6 textviews. I want that when any button is clicked(let's say button 2) then, the text of button 2 should go in the first textview and when another button is clicked(let's say button 4) then the text of button 4 should go in second textview. I don't know what to do for that. I have written code for that please give me some condition for this`package com.aswdc_wordcross;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { Button[] buttons = new Button[4]; TextView[] textViews = new TextView[6]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttons[0] = (Button) findViewById(R.id.Button1); buttons[0].setOnClickListener(this); buttons[1] = (Button) findViewById(R.id.Button2); buttons[1].setOnClickListener(this); buttons[2] = (Button) findViewById(R.id.Button3); buttons[2].setOnClickListener(this); buttons[3] = (Button) findViewById(R.id.Button4); buttons[3].setOnClickListener(this); textViews[0] = (TextView) findViewById(R.id.txtview1); textViews[1] = (TextView) findViewById(R.id.txtview2); textViews[2] = (TextView) findViewById(R.id.txtview3); textViews[3] = (TextView) findViewById(R.id.txtview4); textViews[4] = (TextView) findViewById(R.id.txtview5); textViews[5] = (TextView) findViewById(R.id.txtview6); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.Button1: break; case R.id.Button2: break; case R.id.Button3: break; case R.id.Button4: break; default: break; } } }`
You have 4 Buttons and 6 TextViews, so it is unclear what you want.
To set the text of a TextView you use its setText() method, like:
textViews[1].setText("something");
If you want the text of a Button to be displayed in a TextView:
textViews[1].setText(buttons[1].getText().toString());
So inside onClick()
, implement the logic you want to apply at each case by using the above code like:
case R.id.Button2:
textViews[X].setText(buttons[X].getText().toString());
break;
Edit
If you want to set the text of the 1st TextView
only, I guess this is textViews[0]
,
then you don't need the switch
statement:
@Override
public void onClick(View v) {
Button button = (Button) v;
textViews[0].setText(button.getText().toString());
}
Edit2
If you want to set sequentially the text of the TextView
s
@Override
public void onClick(View v) {
Button button = (Button) v;
for (int i = 0; i < textViews.length; i++) {
if (textViews[i].getTag() == null) {
textViews[i].setText(button.getText().toString());
textViews[i].setTag("0");
break;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.