基本上,我有两个类:
- MyActivity.java
- OtherClass.java
MyActivity.java 概览: 除了实例化 otherClass.java 所需的内容之外,没有什么有趣的东西...
但是MyActivity.layout是一个静态LinearLayout,所以我可以向其中添加视图... 有没有关于如何从另一个类的onClickListner中显示PopUpWindow的建议?
MyActivity.java 概览: 除了实例化 otherClass.java 所需的内容之外,没有什么有趣的东西...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = getApplicationContext() ;
main_activity = this ;
layout = (LinearLayout) findViewById(R.id.layout);
/*
* Do lot of stuff
*/
}
OtherClasse.java概述:
该类包含一个可点击的TextView。当我执行长按事件时,希望显示一个PopUpWindow(在UI线程上,因此与MyActivity相关...)
view.setOnLongClickListener( new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Log.d("TAG", "OnLongClick");
PopupWindow popup = new PopupWindow(activity.getApplicationContext());
//tried with new PopupWindow(MyActivity.context);
popup.setWindowLayoutMode(150, 150);
popup.setContentView( view );
//view corresponds to the TextView.
popup.showAtLocation(MyActivity.layout, Gravity.CENTER_HORIZONTAL, 10, 10);
return true;
}
});
日志显示我进入了 onLongClick() 方法,但是应用程序崩溃了...
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
但是MyActivity.layout是一个静态LinearLayout,所以我可以向其中添加视图... 有没有关于如何从另一个类的onClickListner中显示PopUpWindow的建议?
@Override
public boolean onLongClick(View v) {
PopupWindow popup = new PopupWindow(BlaActivity.context);
TextView tv = new TextView(BlaActivity.context);
LayoutParams para = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(para);
tv.setText("My future text ...");
popup.setContentView(tv);
popup.setWidth(400);
popup.setHeight(180);
popup.showAtLocation(tv, Gravity.CENTER_HORIZONTAL, 10, 10);
popup.update();
return true;
}
返回一个
android.view.WindowManager$BadTokenException: 无法添加窗口--令牌为空无效; 您的活动是否正在运行?
因为popup.showAtLocation(tv, Gravity.CENTER_HORIZONTAL, 10, 10);
调用了public IBinder getWindowToken()
在tv上...显然没有令牌...
popup.setContentView(v);
,我仍然遇到了IllegalStateException异常。 - Oromis L'ancien