【问题标题】:How to get the context from a function of a class that extends Activity in android?如何从在android中扩展Activity的类的函数中获取上下文?
【发布时间】:2017-01-19 15:19:58
【问题描述】:

我有一个扩展 Activity 的类,当我尝试从 onCreate() 方法访问上下文时,它会被打印,但是当我将它保存在变量上下文中并尝试从 committext() 函数访问它时,如下所示, 它打印空。我还尝试直接从committext() 函数中使用“this”和getBaseContext(),因为它是同一类的一部分,我得到空指针异常。请帮我找出问题所在。

public class MainKeyboardActionListener  extends Activity implements KeyboardView.OnKeyboardActionListener, View.OnTouchListener {
    private Context context;
    public static boolean active = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mode_keyboard, false);
        context=getBaseContext();
        System.out.println("contexxtt1"+context);
    }

    @Override
    public void onStart() {
        super.onStart();    
        active = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private static class myHandler extends Handler {
    }
    ;

    public void setInputConnection(InputConnection ic) {    
    }

    @Override
    public void onKey(int arg0, int[] arg1) {
        // TODO Auto-generated method stub    
    }

    @Override
    public void onPress(int keyCode) {
    }

    @Override
    public void onRelease(int keyCode) {
        commitText(String.valueOf(keyCode));
    }

    private void handleException(int keyCode) {
    }

    private void removeHalantMode() {
    }


    private void commitText(String text) {
        if(active==true) {
            System.out.println("contexxtt"+context);
        }
    }

    @Override
    public void onText(CharSequence arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void swipeDown() {
        // TODO Auto-generated method stub
    }

    @Override
    public void swipeLeft() {
        // TODO Auto-generated method stub
    }

    @Override
    public void swipeRight() {
        // TODO Auto-generated method stub
    }

    @Override
    public void swipeUp() {
        // TODO Auto-generated method stub
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        active = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();    
    }
}

【问题讨论】:

  • 你的上下文就是你的活动,所以要引用它你需要这个关键字
  • @firegloves 我试过用这个,不行
  • 发布异常的堆栈跟踪
  • 你在哪里设置你的 KeyboardView.OnKeyboardActionListener, View.OnTouchListener 在某个视图上?我认为 onRelease 永远不会执行。你想达到什么目标?
  • 请发布 mode_keyboard.xml

标签: android android-activity android-context


【解决方案1】:

让你的myHandler 类不是static

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多