这是我的代码:
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.layout_popup);
final View layout = layoutInflater.inflate(R.layout.popup_layout,viewGroup);
final PopupWindow popup = new PopupWindow(GameActivity.this);
Point popupSize = new Point(getResources().getDimensionPixelSize(R.dimen.popup_width),getResources().getDimensionPixelSize(R.dimen.popup_height));
popup.setContentView(layout);
popup.setWidth(popupSize.x);
popup.setHeight(popupSize.y);
popup.setFocusable(true);
File dir = getFilesDir();
File temp = new File(dir.getPath()+"/temp.prj");
try {
if(!temp.exists())temp.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
File[] filesArray = dir.listFiles();
ArrayList<String> files = new ArrayList<>();
for(File file:filesArray)
{
files.add(file.getName());
}
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
popup.showAtLocation(layout, Gravity.NO_GRAVITY, (size.x-popupSize.x)/2, (size.y-popupSize.y)/2);
ListView listView = (ListView)layout.findViewById(R.id.listViewDir);
final EditText fileName = (EditText)layout.findViewById(R.id.editTextFilename);
final StableArrayAdapter adapter = new StableArrayAdapter(GameActivity.this,R.layout.list_item, files);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final TextView item = (TextView) view;
fileName.setText(item.getText());
}
});
导致我麻烦的是:
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final TextView item = (TextView) view;
fileName.setText(item.getText());
}
在我点击列表视图中的项目之后,然后我点击文件名视图和例外
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W@53668b30 is not valid; is your activity running?
被抛出。我尝试在UI线程上运行fileName.setText(item.getText());
,我尝试在许多不同的地方使用MainActivity.this
(或我的变体,GameActivity.this
)。似乎没有什么工作。有谁知道出了什么问题?所有相关问题似乎都围绕着Dialog而不是Popup
更新
出于某种原因,将android:inputType="textNoSuggestions"
添加到xml中的EditText fileName
会停止异常。在列表视图中的项目前面添加一个数字(这意味着它们不会被拼写检查)之后我才注意到这一点。看起来其他人遇到了类似的错误Android ICS spelling error correction causes PopupWindow to crash而且他们也没有答案