문제

누군가가 나를 도울 수 있는지 궁금합니다. SMS를받을 때 토스트 요소를 표시하려고합니다. 이 토스트에는 이미지 (SMS 아이콘)가있는 레이아웃과 2 개의 텍스트 뷰 (Sender, Message)가 포함되어야합니다.

활동에서 다음 방법을 호출하면 예상대로 작동합니다 ...

public void showToast(Context context, String name, String message) {
    LayoutInflater inflater = getLayoutInflater();
    View layout = inflater.inflate(R.layout.toast_sms,
                                   (ViewGroup) findViewById(R.id.toast_sms_root));

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

    Toast toast = new Toast(getApplicationContext());
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();
}

그러나 SMSReceiver와 동일한 방식으로 동일한 코드를 호출하려고하면 다음과 같이받습니다.

The method getLayoutInflater() is undefined for the type SmsReceiver
The method findViewById(int) is undefined for the type SmsReceiver
The method getApplicationContext() is undefined for the type SmsReceiver

누군가 내가 의도에서 TIH를 어떻게 할 수 있는지 조언 할 수 있습니까? 문제가 어떻게 든 교차 스레딩과 관련이 있다고 생각하지만 어떻게 진행 해야할지 잘 모르겠습니다. 온라인에서 몇 가지 예를 보았지만 더 이상 사용되지 않은 코드를 사용하거나 간단한 텍스트 만 표시하는 것 같습니다.

누군가 나를 올바른 방향으로 가리킬 수 있습니까?

많은 감사합니다

도움이 되었습니까?

해결책

LayoutInflater.from (Context)을 사용하여 LayoutInflater를 얻을 수 있습니다. 이와 같이:

LayoutInflater mInflater = LayoutInflater.from(context);
View myView = mInflater.inflate(R.layout.customToast, null);
TextView sender = (TextView) myView.findViewById(R.id.sender);
TextView message = (TextView) myView.findViewById(R.id.message);

다른 팁

컴파일 오류는 그 때문입니다 BroadcastReceiver 상속하지 않습니다 Context. 사용 Context 그것은 전달됩니다 onReceive() (그리고 제거하십시오 getApplicationContext() - 그냥 사용하십시오 Context 당신은 지나갔습니다).

이제 5 월 아직 당신이 Toast a BroadcastReceiver 우선, 그러나 이것은 최소한 컴파일 오류를 지나쳐 줄 것입니다.

방송 수신기가 아닌 활동이나 서비스에서 토스트를 만들어 표시 할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top