“setView must have been called” - Custom Class extending button

房东的猫 提交于 2019-12-05 21:15:21

Change the lines of code below, to the one's that follow:

        Toast toast = new Toast(context);
        Toast.makeText(context, tileID, Toast.LENGTH_SHORT);
        toast.show();

Change to this:

    Toast toast = Toast.makeText(context, tileID, Toast.LENGTH_SHORT);
    toast.show();       

As you can see from the source code, that exception is thrown only when mNextView is null. The function "makeText" is suppose to set it, and it does, but your original code does not capture the reference to the Toast it builds. Instead, your original code creates two Toasts, and attempts to "show" the one which has not yet had its view set.

public void show() {
    if (mNextView == null) {
        throw new RuntimeException("setView must have been called");
    }

....

public static Toast makeText(Context context, CharSequence text, int duration) {
    Toast result = new Toast(context);

    LayoutInflater inflate = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
    TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
    tv.setText(text);

    result.mNextView = v;
    result.mDuration = duration;

    return result;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!