开发者

editing a global variable

Hi im new to android and I have a program that has a global variable define and it works, so I can set it and get it in every activity, BUT it dosnt like to be changed in an on click listener. I made it so on the screen there is an edittext and when someone presses a button I want the edittext text to be put into the global variable. here is my code:

Button SiteButton = (Button) findViewById(R.id.SiteButton);
    SiteButton.setOnClickListener(new View.OnClickListener() {
        TextView textviewS = (TextView) findViewById(R.id.SiteIdT);
        EditText edittextS = (EditText) findViewById(R.id.SiteIdE);
        TextView textviewB = (TextView) findViewById(R.id.B开发者_开发技巧usIdT);
        EditText edittextB = (EditText) findViewById(R.id.BusIdE);
        public void onClick(View v) {
            textviewS.setText(edittextS.getText());
            ((Global) this.getApplication()).setgSiteId(textviewS.getText().toString());
            textviewB.setText(edittextB.getText()); 
            ((Global) this.getApplication()).setgVehicleId(textviewB.getText().toString());
        }
    });

but the getApplication() part is showing an error. can anyone help?


You should refer to your activity this, since View.OnClickListener doesn't have such a method:

// Bad code! read below
((Global) MyActivityClassName.this.getApplication()).setgSiteId(textviewS.getText().toString());
textviewB.setText(edittextB.getText()); 
((Global) MyActivityClassName.this.getApplication()).setgVehicleId(textviewB.getText().toString());

By the way, how do you cast the return from getApplication() to Global? You will get a class cast exception there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜