【问题标题】:Increase TextView by integer variable [duplicate]通过整数变量增加TextView [重复]
【发布时间】:2016-09-27 21:45:07
【问题描述】:

我有一个带有简单 onClick 方法的按钮。每次单击按钮时,我都希望我的 TextView 增加 1。例如,我的 TextView 显示 0 当单击按钮时,它应该显示 1,当再次单击按钮时,它应该显示 2...等等。我希望我的观点很清楚;)

公共类游戏扩展Activity {

ViewGroup layout;
TextView score1;
String score;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);

    score1 = (TextView)findViewById(R.id.textView5);

    score = score1.getText().toString();

    layout = (ViewGroup) findViewById(R.id.frameLayout2);
    layout.setOnTouchListener(
            new RelativeLayout.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    String presentValStr=score1.getText().toString();
                    int presentIntVal=Integer.parseInt(presentValStr);
                    presentIntVal++;
                    score1.setText(String.valueOf(presentIntVal));

                    return true;
                }
            }

                );
}

【问题讨论】:

    标签: android onclick textview integer addition


    【解决方案1】:
    private int count=0; 
    
    @Override public void onClick(View v) {
         count++;
         textView.setText(Integer.toString(count));
    }
    

    【讨论】:

    • 首先谢谢您,您的代码可以正常工作,但 textview 总是增加一个随机数而不是数字 1。
    • 你的意思是这段代码增加了一个随机数吗?如果您向我展示您的代码,我可以为您提供更好的帮助。
    • 我把我的代码放在问题部分。
    • 它不是随机的,但您应该使用 setOnClickListener 而不是 setOnTouchListener,因为 OnTouch 检测到 3 个操作(ACTION_DOWN、ACTION_MOVE、ACTION_UP),因此您只需单击一次视图,您的代码就会执行 3 次。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多