2017-05-17 9 views
-4

このアクティビティでは、showCustomAlertメソッドがあります。このメソッドは、別のアクティビティを呼び出す必要があります。コンテキストレイアウトインフレータをandroidの別のアクティビティに呼び出す方法

public void showCustomAlert(Context context , int message) { 
     try { 

     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View layout = inflater.inflate(R.layout.custom_toast, 
     (ViewGroup) findViewById(R.id.custom_toast_layout)); 

     TextView text = (TextView) layout.findViewById(R.id.textToShow); 

     text.setText(message); 

     Toast toast = new Toast(getApplicationContext()); 
     toast.setDuration(Toast.LENGTH_LONG); 
     toast.setView(layout); 
     toast.show(); 

    } catch (Exception e) { 
     e.getMessage(); 
    } 
} 

これは私がshowCustomAlertメソッドを呼び出す別のアクティビティです。エラーnullポインタ例外が発生しています。

Toss toast = new Toss(); 
toast.showCustomAlert(this , R.string.error_toast); 
+0

ポストフル* Logcatをするのに役立ちます。 –

+0

ポストスタックタール – FAT

+0

custom_toastとcustom_toast_layout XMLを投稿できますか? – FAT

答えて

0

私はこの問題は、あなたのshowCustomAlert()方法であると思います。

custom_layoutを膨張、null代わりに(ViewGroup) findViewById(R.id.custom_toast_layout)としてViewGroupを使用します。

View layout = inflater.inflate(R.layout.custom_toast, null); 

Toastのインスタンスを作成する場合、使用がcontext代わりにgetApplicationContext()を受けました。

Toast toast = new Toast(context); 

次のようにあなたのToss.javaクラスを更新します。ここでは

import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.TextView; 
import android.widget.Toast; 

public class Toss { 

    public void showCustomAlert(Context context , int message) { 

     try { 
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

      View layout = inflater.inflate(R.layout.custom_toast, null); 

      TextView text = (TextView) layout.findViewById(R.id.textToShow); 
      text.setText(message); 

      Toast toast = new Toast(context); 
      toast.setDuration(Toast.LENGTH_LONG); 
      toast.setView(layout); 
      toast.show(); 

     } catch (Exception e) { 
      e.getMessage(); 
     } 
    } 
} 

は、サンプルcustom_toast.xmlです:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="#ff0000" 
    android:padding="8dp"> 

    <TextView 
     android:id="@+id/textToShow" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:textColor="#ffffff"/> 

</LinearLayout> 

使用します。

Toss toast = new Toss(); 
toast.showCustomAlert(this , R.string.error_toast); 

ここで、R.string.error_toastには、テキストThis is a custom error toastが含まれています。

OUTPUT:

enter image description here

ホープこれは*〜

関連する問題