从OnClick()调用Activity的功能

时间:2014-10-13 15:36:58

标签: android android-activity onclick runtime android-context

我有那段代码:

public class GeolocationActivity extends ActionBarActivity implements SensorEventListener {
{
    //...

    private void setUpCompass()
    {
        isCompass = true;
        setContentView(R.layout.subactivity_compass);
        //...
    }

    private void setUpMain()
    {
        //...

        btn2 = (Button)findViewById(R.id.geoloc_compass);
        btn2.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) {
                // here I want to call method setUpCompass();
            }
        });
        //...

    }           
}

我想从setUpCompass()中的onClick()函数调用setUpMain()方法。

我试过了:

Context c = getBaseContext();
((GeolocationActivity)c).setUpCompass();

但我明白了:

java.lang.ClassCastException: android.app.ContextImpl cannot be cast to com.myname.myapp.GeolocationActivity

我做错了什么?

1 个答案:

答案 0 :(得分:1)

而是简单地使用GeolocationActivity.this

示例:

GeolocationActivity.this.setUpCompass();