You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android按钮点击填充TextView问题求助:代码逻辑补全建议

解决方案:实现按钮文本依次填充TextView的逻辑

嘿,我来帮你完善这个点击事件的逻辑!核心是用一个计数器跟踪下一个要填充的TextView位置,这样不管点击哪个按钮,都能按顺序把文本填入对应的TextView里。

步骤1:添加计数器成员变量

首先在MainActivity类里添加一个私有的成员变量,用来记录当前该填充第几个TextView:

private int currentTextViewIndex = 0; // 初始指向第一个TextView

步骤2:优化onClick方法逻辑

你原来的switch分支其实可以简化,因为所有按钮的处理逻辑都是一致的——把按钮文本填入当前索引的TextView,然后移动到下一个位置。修改后的onClick方法如下:

@Override
public void onClick(View v) {
    // 先判断是否还有未填充的TextView
    if (currentTextViewIndex < textViews.length) {
        // 把点击的控件转为Button对象,获取它的文本
        Button clickedButton = (Button) v;
        // 将文本填入当前索引的TextView
        textViews[currentTextViewIndex].setText(clickedButton.getText());
        // 计数器自增,下次点击就填下一个TextView
        currentTextViewIndex++;
    }
    // 如果已经填满6个TextView,就不再处理后续点击
}

完整修改后的代码

这里是整合后的完整代码,方便你直接参考:

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]; 
    private int currentTextViewIndex = 0; // 新增计数器变量

    @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) { 
        if (currentTextViewIndex < textViews.length) {
            Button clickedBtn = (Button) v;
            textViews[currentTextViewIndex].setText(clickedBtn.getText());
            currentTextViewIndex++;
        }
    } 
}

逻辑说明

  • currentTextViewIndex初始为0,对应第一个TextView(textViews[0])
  • 每次点击任意按钮,先检查计数器是否小于TextView数组的长度(也就是还没填满6个)
  • 如果可以填充,就把点击按钮的文本设置到当前索引的TextView,然后计数器加1,下次点击就会自动定位到下一个TextView
  • 当所有6个TextView都填满后,后续的按钮点击就不会再触发填充操作,避免数组越界错误

内容的提问来源于stack exchange,提问作者Bhavdip Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:43:48