2015-12-03 37 views
1

我有這個問題: 我想在抽屜頭部顯示一個textview,我想在用戶打開它時改變這個textview,但是當textview不是顯示(他滾動菜單)textview爲NULL,應用程序停止(顯然)。Android:當抽屜沒有顯示時,textview爲null

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"); 
      } ... 

此代碼在顯示文本視圖時起作用。

我把「if(t!= null)」,但它只是使應用程序不關閉自己。你能告訴我一個更好的解決方案嗎? 謝謝!

+0

試舉'T =(TextView的)findViewById(R.id.drawer_time);' 出塊'onDrawerOpened' – phongvan

+0

我做它,但不起作用... :( – oscargc

回答

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); 
0

嘗試從drawer(DrawerLayout)找到drawer_time TextView的。

更改行:

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

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