在安卓中自定义Toast

3

我正在尝试使用以下方法更改我的应用程序中toast的背景和文本颜色:


LayoutInflater infator = getLayoutInflater();
            View layout =infator.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toast_layout));
            TextView toastText = (TextView) findViewById(R.id.toasttext);
            toastText.setBackgroundColor(Color.YELLOW);
            toastText.setText("uei:"+o.getUei());
            Toast toast = new Toast(getApplicationContext());
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setView(layout);
            toast.show();

这段代码存在于我的ListView的OnItemClickListener中。
但应用程序会出现空指针异常导致崩溃!
这是在onClick监听器之上的内容,它可以提供更好的理解。
public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alarms);
        m_alarmAdapter = new AlarmAdapter(this, R.layout.severity_item, m_alarms);
        setListAdapter(m_alarmAdapter);
        ListView lv = getListView();
                lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
                Log.d(TAG, "clicked: " + view);
                final Alarm o = m_alarmAdapter.getItem(position);
                LayoutInflater infator = getLayoutInflater();

LogCat中的简要错误报告 08-25 13:25:14.672: ERROR/AndroidRuntime(2879): java.lang.NullPointerException 08-25 13:25:14.672: ERROR/AndroidRuntime(2879): at com.opennms.android.AlarmActivity$2.onItemClick(AlarmActivity.java:65) - TechnocraT
你是否在 findViewById 之前调用了 setContentView - MByD
@Zeisss 第65行是toastText.setBackgroundcolor... @MByD 我在onCreate()方法中立即设置了其他alarm.xml文件的内容视图。 - TechnocraT
@technocrat:那么toastText是null,因此findViewById()返回null,所以toasttext似乎不是您的内容视图的一部分。 - ZeissS
@Zeisss 是的,看起来是这样,但我在toast.xml中指定了id为toasttext的textview。同时,我正在使用inflator获取toast.xml。那么解决方案可能是什么呢? - TechnocraT
1个回答

1
您正在要求当前视图查找toasttext id,而不是刚刚加载的视图。请尝试使用layout.findViewById()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接