Sunday 1 April 2012

Disable outside PopupWindow, by setFocusable(true)

In the last exercise of "Example of using PopupWindow", user still can touch on views/widgets outside PopupWindow. We can call PopupWindow.setFocusable(true), the PopupWindow will grab the focus from the current focused widget if the popup contains a focusable View. Such that the "Open Popup Window" will be disabled.

package com.exercise.AndroidPopupWindow;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;

public class AndroidPopupWindowActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final Button btnOpenPopup = (Button)findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);

final Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
btnDismiss.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(AndroidPopupWindowActivity.this,
"Dismiss", Toast.LENGTH_LONG).show();
popupWindow.dismiss();
}});

popupWindow.showAsDropDown(btnOpenPopup, 50, -30);

//---

popupWindow.setFocusable(true);
popupWindow.update();

//---

}});
}
}


No comments:

Post a Comment