简体   繁体   English

TextView SetText

[英]TextView SetText

I have a problem. 我有个问题。
In line " textView.setText(money + "$"); " my program crashes. 在“ textView.setText(money + "$"); “行中,我的程序崩溃了。
( money is int , and textView1 is ID of my TextView ) moneyinttextView1是我的TextView ID

public TextView textView;
public void onCashClick(View view) {
            money++;
            textView = (TextView) view.findViewById(R.id.textView1);
            textView.setText(money + "$");
        }

Thanks for help, and sorry for my bad English. 感谢您的帮助,对不起我的英语不好。

The following line makes your app crash. 以下行使您的应用程序崩溃。 Because the view sent from the click is the button, not the container. 因为单击发送的视图是按钮,而不是容器。 Therefore, the button doesn't contain your textview. 因此,该按钮不包含您的textview。 You should be getting NullPointerException on that line. 您应该在该行上获取NullPointerException。 Instead, you should define textView on onCreate method: 相反,您应该在onCreate方法上定义textView:

textView = (TextView) findViewById(R.id.textView1);

and only after, onCashClick call: 并且只有在onCashClick调用之后:

on button click. 在按钮上单击。

UPDATE: change your code to the following, 更新:将您的代码更改为以下内容,

public TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    textView = (TextView) view.findViewById(R.id.textView1);
   }

public void onCashClick(View view) {
        money++;
        textView.setText(money + "$");
    }

因为用于绑定文本视图的视图是单击按钮,而不是使用view.findViewById()(如果您处于活动状态),只需使用findViewById;如果您处于片段中,则使用rootView。

只需删除findViewByID之前的view即可

textView = (TextView) findViewById(R.id.textView1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM