这是一个类似于许多其他关于BadTokenException: Unable to add window - is your activity running?
简而言之,我有一个有两个Spinners
的弹出窗口。当我在模拟器中单击它们时,一切正常。但是,在使用我的设备时,我会遇到异常:
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W@b3b2e85 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:679)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:341)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
at android.widget.PopupWindow.invokePopup(PopupWindow.java:1417)
at android.widget.PopupWindow.showAsDropDown(PopupWindow.java:1259)
at android.widget.ListPopupWindow.show(ListPopupWindow.java:683)
at android.widget.Spinner$DropdownPopup.show(Spinner.java:1235)
at android.widget.Spinner.performClick(Spinner.java:770)
。
不同的主题表明它与bad context
有关。我尝试了不同的上下文,例如getActivity(),
getBaseContext()
和getApplicationContext()
。他们都没有帮助。我也像一些人建议的那样测试isfinishing()
。
如果我在xml文件中使用android:spinnerMode="dialog"
,它可以在我的设备上运行。但如果我使用dropdown
则失败。
这是我的代码:
package com.example.erikbylow.autoflash;
import android.content.Context;
import android.content.Intent;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import com.example.erikbylow.autoflash.utils.FileHandler;
import android.view.LayoutInflater;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity{
final static public String SOURCE_LANG = "source_lang";
final static public String TARGET_LANG = "target_lang";
MainActivityFragment mainFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainFragment = new MainActivityFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.main_layout, mainFragment).commit();
}
private void deleteAllFiles(){
FileHandler fHandler = new FileHandler();
fHandler.deleteAllFiles(getApplicationContext());
}
private void printFiles(){
FileHandler fileHandler = new FileHandler();
ArrayList<String> fileNames = fileHandler.getFileNames(getApplicationContext());
for (String s : fileNames){
Log.e("Main Files", s);
}
}
public void start_translation(View v){
if (!isFinishing()) {
mainFragment.showPopup(); // Here the popup is shown
} else {
System.out.println("IsFinishing!!");
}
}
public void start_training(View v){
Intent intent = new Intent(this,TrainActivity.class);
startActivity(intent);
}
}
MainActivity Fragment
package com.example.erikbylow.autoflash;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.Spinner;
import com.example.erikbylow.autoflash.testCode.TestCardView;
import java.util.ArrayList;
import java.util.Arrays;
import static android.content.Context.LAYOUT_INFLATER_SERVICE;
/**
* Created by erikbylow on 2017-12-29.
*/
public class MainActivityFragment extends Fragment {
private String source_language;
private String target_language;
final private String SOURCE_ID = "source";
final private String TARGET_ID = "target";
final static public String SOURCE_LANG = "source_lang";
final static public String TARGET_LANG = "target_lang";
private ArrayList<String> acronyms;
private String src;
private String target;
private PopupWindow mPopupWindow;
public MainActivityFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_main_acitivity,container,false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
View customView = getActivity().getLayoutInflater().inflate(R.layout.select_language,null);
mPopupWindow = getSelectPopup(customView);
// Set acronyms
acronyms = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.array_acronyms)));
setSpinnerListeners(customView);
setCtnButton(customView);
}
// Created the popup warning
private void setSpinnerListeners(View view){
Spinner spinner1 = view.findViewById(R.id.spinner1);
Spinner spinner2 = view.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.array_languages, android.R.layout.simple_spinner_item);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(), R.array.array_languages, android.R.layout.simple_spinner_item);
spinner1.setAdapter(adapter1);
spinner2.setAdapter(adapter2);
if(spinner1==null || spinner2 == null){
System.out.println("NULL ON SPINNER");
}
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
src = acronyms.get(pos);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
target = acronyms.get(pos);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setCtnButton(View view){
Button button = view.findViewById(R.id.start_translate_btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),TranslateActivity.class);
intent.putExtra(SOURCE_LANG,src);
intent.putExtra(TARGET_LANG,target);
startActivity(intent);
mPopupWindow.dismiss();
}
});
}
private PopupWindow getSelectPopup(View view){
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
float row = 300*metrics.density;
float cols = 200*metrics.density;
PopupWindow tmp = new PopupWindow(
view,(int)row,(int)cols);
ImageButton closeButton = (ImageButton) view.findViewById(R.id.ib_close);
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPopupWindow.dismiss();
}
});
return tmp;
}
public PopupWindow getPopupWindow(){
return mPopupWindow;
}
public void showPopup(){
mPopupWindow.showAtLocation(getView(), Gravity.CENTER, 0, 0);
}
}
MainFragmentLayout.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout_fragment"
tools:context="com.example.erikbylow.autoflash.MainActivity"
tools:showIn="@layout/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Button
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Start Translation"
android:clickable="true"
android:onClick="start_translation"/>
<Button
android:layout_marginTop="30dp"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Start Training"
android:clickable="true"
android:onClick="start_training"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/main_layout"
/>
PopupViewLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_custom_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
android:orientation="vertical"
android:background="#ab2fc4"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageButton
android:id="@+id/ib_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_delete"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="@null"
/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:text="@string/set_source"/>
<Spinner
android:layout_gravity="center"
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/array_languages"
android:prompt="@string/set_source" />
<TextView
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:text="@string/set_target"/>
<Spinner
android:layout_gravity="center"
android:id="@+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/array_languages"
android:prompt="@string/set_source" />
<Button
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Continue"
android:textAlignment="center"
android:id="@+id/start_translate_btn"/>
</LinearLayout>