当我使用new Button(this)动态创建新按钮时发生错误

时间:2019-08-27 15:34:20

标签: java android

我想使用“ Button btn = new Button(this)”动态创建按钮,但是发生了错误

我还使用“ Button btn = new Button(MainActivity.this)”,但是没有用

//this code is in a thread
Thread uiUpdate = new UIUpdate(expressInfo,btnIndex);
uiUpdate.start();





public class UIUpdate extends Thread{
    private String btnText;
    private int btnIndex;
    public UIUpdate(String btnText,int btnIndex){
        this.btnIndex = btnIndex;
        this.btnText = btnText;
    }

    @Override
    public void run(){
        Message message = new Message();
        message.obj = createButton(btnText,btnIndex);
        message.what = ADD_EXPRESS_INFO;
        handler.sendMessage(message);
    }
}

//add button dynamically
private Handler handler = new Handler(){
    public void handleMessage(Message msg){
        switch (msg.what){
            case ADD_EXPRESS_INFO:
                //add button to LinearLayout
                expressLayout.addView((Button)msg.obj);
                break;
            default:
                break;
        }
    }
};


protected Button createButton(String info,int index){

    Button btn = new Button(MainActivity.this);// error occurs!!!
    Log.d("debug","btn info: "+btn);
    //button setting
    btn.setId(index);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
    btn.setLayoutParams(layoutParams);
    btn.setText(info);
    return btn;
}

“ java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.content.res.Resources android.content.Context.getResources()'”

0 个答案:

没有答案