按下按钮创建弹出窗口

时间:2016-01-01 01:01:07

标签: android

我想在片段中创建一个弹出窗口。弹出窗口将在按下按钮时创建,并在按下按钮时销毁。这是我目前的代码,但窗口没有显示或无法看到。

在片段类中:

这是按钮

的OnTouchListener方法
Button button2 = (Button) view.findViewById(R.id.res_weak_button);
    button2.setOnTouchListener(
            new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        Log.w("PokeApp", "DOWN");
                        createPopupVisuals();
                        return true;
                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
                        Log.w("PokeApp", "UP");
                        popupMessage.dismiss();
                        return true;
                    }
                    return false;
                }
            }
    );

这是创建弹出窗口的方法

private void createPopupVisuals(){

    RelativeLayout layout = new RelativeLayout(getActivity());
    TextView resist = new TextView(getActivity());
    resist.setText("Pokemon is resistant to:");
    TextView weakness = new TextView(getActivity());
    weakness.setText("Pokemon is weak against:");

    RelativeLayout.LayoutParams resistParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT
    );
    RelativeLayout.LayoutParams weaknessParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT
    );
    weaknessParams.addRule(RelativeLayout.BELOW, resist.getId());
    weaknessParams.setMargins(0,40,0,0);

    resist.setLayoutParams(resistParams);
    weakness.setLayoutParams(weaknessParams);

    layout.addView(resist);
    layout.addView(weakness);

    //TODO: Get types

    popupMessage = new PopupWindow(layout, RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    popupMessage.setContentView(layout);
    Log.w("PokeApp", "Should have created layout");
}

1 个答案:

答案 0 :(得分:0)

我只是忘了在底部添加这一行。

popupMessage.showAsDropDown(aButton, 0, 0);

它现在完美无缺