我正在尝试通过以下在线视频教程来学习 Android 。
我看过一个视频如何创建自定义Toast消息。
我跟着同样的事情。但是在显示吐司信息(关闭时)后我得到致命异常。
例外如下::
04-28 21:36:03.726: E/AndroidRuntime(2417): FATAL EXCEPTION: main
04-28 21:36:03.726: E/AndroidRuntime(2417): java.lang.IllegalArgumentException: View not attached to window manager
04-28 21:36:03.726: E/AndroidRuntime(2417): at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:355)
04-28 21:36:03.726: E/AndroidRuntime(2417): at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:200)
04-28 21:36:03.726: E/AndroidRuntime(2417): at android.widget.Toast$TN.handleShow(Toast.java:370)
04-28 21:36:03.726: E/AndroidRuntime(2417): at android.widget.Toast$TN$1.run(Toast.java:302)
04-28 21:36:03.726: E/AndroidRuntime(2417): at android.os.Handler.handleCallback(Handler.java:587)
04-28 21:36:03.726: E/AndroidRuntime(2417): at android.os.Handler.dispatchMessage(Handler.java:92)
04-28 21:36:03.726: E/AndroidRuntime(2417): at android.os.Looper.loop(Looper.java:130)
04-28 21:36:03.726: E/AndroidRuntime(2417): at android.app.ActivityThread.main(ActivityThread.java:3687)
04-28 21:36:03.726: E/AndroidRuntime(2417): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 21:36:03.726: E/AndroidRuntime(2417): at java.lang.reflect.Method.invoke(Method.java:507)
04-28 21:36:03.726: E/AndroidRuntime(2417): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
04-28 21:36:03.726: E/AndroidRuntime(2417): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
04-28 21:36:03.726: E/AndroidRuntime(2417): at dalvik.system.NativeStart.main(Native Method)
MainActivity.Java
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showCustomToast(View v)
{
Toast toast = new Toast(this);
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 0);
LayoutInflater lin = getLayoutInflater();
View appear = lin.inflate(R.layout.custom,
(ViewGroup)findViewById(R.id.LinearLayout1));
toast.setView(appear);
toast.show();
}
}
custom.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ganesh" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ganesh"
android:textAppearance="?android:attr/textAppearanceLarge" />
答案 0 :(得分:0)
尝试使用应用的上下文设置祝酒词:
Toast toast = new Toast(MainActivity.this);