我有一个Android活动,按下某个按钮时会打开 pop_up窗口,此pop_up包含取消按钮 取消它按下时,但是当pop_up打开并按下取消按钮时,此按钮不起作用,我不知道为什么,这是我的代码:
爪哇:
private PopupWindow pw;
private ImageButton TVShowposter;
private void initiatePopupWindow(String section) {
try {
View layout = null;
// to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) Media.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Inflate the view from a predefined XML layout
if (section.equals("Music")) {
layout = inflater.inflate(R.layout.music_popup,
(ViewGroup) findViewById(R.id.music_pop));
// create a 300px width and 470px height PopupWindow
pw = new PopupWindow(layout,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
// display the popup in the center
pw.showAtLocation(layout, Gravity.CENTER, 0, 0);
Button cancel = (Button) findViewById(R.id.back_music);
cancel.setOnClickListener(onCancelClick);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private OnClickListener onCancelClick = new OnClickListener() {
public void onClick(View v) {
pw.dismiss();
}
};
XML(按钮部分):
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<Button
android:id="@+id/back_music"
android:background="@drawable/gradient_popups"
android:text="@string/cancel"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:textColor="@android:color/white"
android:clickable="true" />
<TextView
android:id="@+id/music_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/music"
android:textColor="@android:color/white"
android:textSize="13sp"
android:layout_gravity="center" />
</LinearLayout>
答案 0 :(得分:2)
您只需创建如下按钮:
Button close=(Button)layout.findViewById(R.id.close_btn);
这是供参考。
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}
});
您在此处代码中的错误:
Button cancel = (Button) findViewById(R.id.back_music);
答案 1 :(得分:1)
你的按钮实际上有引用问题,你只需要从弹出的布局中调用findviewbyid方法,如下所示: -
Button cancel = (Button) layout.findViewById(R.id.back_music);
cancel.setOnClickListener(onCancelClick);