Android:当文档未显示时,textview在抽屉中为空

时间:2015-12-03 01:13:19

标签: android nullpointerexception navigation-drawer

我有这个问题: 我想在抽屉标题中显示一个textview,我希望在用户打开它时更改此textview,但是当没有显示textview时(他向下滚动菜单)textview为NULL并且应用程序停止(显然)。 / p>

 drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close){

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            t = (TextView) findViewById(R.id.drawer_time);
            long new_time = System.currentTimeMillis();
            long update = ((new_time - old_time) / 60000);
            if (update > 0 && update < 60) {
                t.setText("Updated " + update + " min. ago");
            } ...

此代码在显示文本视图时有效。

我把&#34; if(t!= null)&#34;,但它只是让应用程序自己关闭。你能告诉我一个更好的解决方案吗? 谢谢!

2 个答案:

答案 0 :(得分:0)

t==null //because findViewById finds subview from which layout is showing.


t = (TextView) findViewById(R.id.drawer_time);

装置

t = (TextView) layout.findViewById(R.id.drawer_time);//layout : which you can see from the screen.

你可以试试这个:

View view = LayoutInflater.from(context).inflate(R.layout.yourlayout, null);
t = (TextView) view.findViewById(R.id.drawer_time);

答案 1 :(得分:0)

尝试从drawer_time找到drawer(DrawerLayout) Textview。

更改行:

t = (TextView) findViewById(R.id.drawer_time);

t = (TextView) drawer.findViewById(R.id.drawer_time);