【问题标题】:custom toast in fragment片段中的自定义吐司
【发布时间】:2015-01-04 16:08:12
【问题描述】:

我有简单的自定义吐司,它在类范围活动中工作正常,但在 片段 中我有一个问题。 findviewbyid 方法在片段中不起作用!!
我该如何解决?

LayoutInflater inflater = getLayoutInflater();
    View layouttoast = inflater.inflate(R.layout.customtoast, (ViewGroup)findViewById(R.id.toastcustom));
    ((TextView) layouttoast.findViewById(R.id.texttoast)).setText(message);

layouttoast.findViewById(R.id.imagetoast)).setBackgroundResource(R.drawable.icon);



    Toast mytoast = new Toast(getBaseContext());
    mytoast.setView(layouttoast);
    mytoast.setDuration(Toast.LENGTH_LONG);
    mytoast.show();

【问题讨论】:

    标签: android android-fragments android-toast


    【解决方案1】:

    您应该将代码放在FragmentonCreateView 方法下,然后从片段膨胀的视图中调用findViewById 方法,如下所示:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View parent = inflater.inflate(R.layout.your_fragment_layout, container, false);
    
        View layouttoast = inflater.inflate(R.layout.customtoast,(ViewGroup)parent.findViewById(R.id.toastcustom));
        ((TextView) layouttoast.findViewById(R.id.texttoast)).setText(message);
    
        layouttoast.findViewById(R.id.imagetoast)).setBackgroundResource(R.drawable.icon);
    
    
    
        Toast mytoast = new Toast(getBaseContext());
        mytoast.setView(layouttoast);
        mytoast.setDuration(Toast.LENGTH_LONG);
        mytoast.show();
        return parent;
    }
    

    【讨论】:

    • 不错的答案,但是如果我有 asyncktask..并且在我的 asynctask 中我想使用自定义 toast..你能帮我解决这个问题吗?
    • 您的 AsyncTask 是否在片段中?
    • 函数返回后不能做任何事情。如果你想在 'onPostExecute()'、'onPreExecute()' 方法中显示自定义 toast,答案是一样的,除了你应该使用 'getView()' 方法而不是膨胀 'parent'。
    • 我正在尝试添加 doinbackgroundmethod ..我创建 runonuithread ..在该 runonuithread 中我想使用自定义 toast ..
    • 看这个要点,我已经创建了...gist.github.com/rom4ek/e7b8db27829d10c6b143
    【解决方案2】:

    试试这个并相应地更改布局和 ID:

    LayoutInflater inflater1 = getActivity().getLayoutInflater();
    
    View layout = inflater1.inflate(R.layout.custom_toast, (ViewGroup) getActivity().findViewById(R.id.custom_toast_layout_id));
    
    // set a message
    TextView text = (TextView) layout.findViewById(R.id.text);
    text.setText("Custom Toast");
    
    // Toast...
    Toast toast = new Toast(getActivity().getApplicationContext());
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      相关资源
      最近更新 更多