简体   繁体   中英

TextView SetText

I have a problem.
In line " textView.setText(money + "$"); " my program crashes.
( money is int , and textView1 is ID of my TextView )

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. You should be getting NullPointerException on that line. Instead, you should define textView on onCreate method:

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

and only after, onCashClick call:

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);

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.

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