Section1
代码如下
public class MainActivity extends AppCompatActivity { private LinearLayout ll_main; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ll_main = (LinearLayout) findViewById(R.id.ll_main); PopupWindow popupWindow = new PopupWindow(this); popupWindow.setContentView(View.inflate(this,R.layout.layout_popup,null)); findViewById(android.R.id.content); popupWindow.showAsDropDown(ll_main); } }
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
Section2 报错了,修改代码如下
private LinearLayout ll_main; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ll_main = (LinearLayout) findViewById(R.id.ll_main); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); PopupWindow popupWindow = new PopupWindow(this); popupWindow.setContentView(View.inflate(this,R.layout.layout_popup,null)); findViewById(android.R.id.content); popupWindow.showAsDropDown(ll_main); }
这次是不报错了,但是popupwindow还是没有出来。
Section3
难道是因为inflate的时候没有指定parent?
public class MainActivity extends AppCompatActivity { private LinearLayout ll_main; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ll_main = (LinearLayout) findViewById(R.id.ll_main); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); PopupWindow popupWindow = new PopupWindow(this); popupWindow.setContentView(View.inflate(this, R.layout.layout_popup, ll_main)); findViewById(android.R.id.content); popupWindow.showAsDropDown(ll_main); } }
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
更不对,因为这个view并不是ll_main的child,ll_main作为parent显然是错误的
Section4
到底是什么原因,其实原因很简单,因为popWindow new 的时候需要指定宽高,
我们继续修改代码
public class MainActivity extends AppCompatActivity { private LinearLayout ll_main; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ll_main = (LinearLayout) findViewById(R.id.ll_main); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); PopupWindow popupWindow = new PopupWindow(100,100); popupWindow.setContentView(View.inflate(this,R.layout.layout_popup,null)); findViewById(android.R.id.content); popupWindow.showAsDropDown(ll_main); } }
这次终于出来了。