2014-07-24 57 views
0

我想在Activity接口出現在onCreate()更新TextView,使文本應設置,我已經試過是:中的onCreate()更新的TextView

Java代碼:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_sem_selection); 

    TextView T =(TextView)findViewById(R.id.textView1); 
    T.setText("required text"); 

    if (savedInstanceState == null) { 
     getSupportFragmentManager().beginTransaction() 
       .add(R.id.container, new PlaceholderFragment()).commit(); 
    } 
} 

但活動開始時我收到錯誤,只要我評論此行:

T.setText("required text"); 

應用程序正常運行正常,沒有錯誤。我應該怎麼做?還有其他方法嗎?

+0

你的'textView1'可能在'PlaceholderFragment'中。將它移動到'onCreateView' – Apoorv

+0

什麼錯誤?發佈你的LogCat/Stacktrace – Sufian

+0

是的,這必須在裏面onCreatView(),解決了它:) –

回答

1

您從fragment引用TextView T因爲在你的活動中,你正在使用activity_sem_selectionactivity_sem_selection佈局得到的TextView T你會得到空。

所以用TonCreateView方法分段。

例如

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment__sem_selection, container, 
       false); 

     TextView T =(TextView)rootView.findViewById(R.id.textView1); 
     T.setText("required text"); 

     return rootView; 
    } 

注:改變​​與片段佈局。

+1

而且,最好使用小寫字母的變量 - 'TextView t'而不是'T' – gilonm

+0

非常感謝#Giru bhai :)它完美的工作,現在我不能得到我以前犯的錯誤,這是一個空指針異常,我是一個初學者,善良詳細,在此先感謝。 –

+0

@ÅdəəlÅhmåd樂意提供幫助,不要忘記接受答案。 –

0

刪除

if (savedInstanceState == null) { 
    getSupportFragmentManager().beginTransaction() 
      .add(R.id.container, new PlaceholderFragment()).commit(); 
    } 
0

檢查textView1存在於activity_sem_selection layout.Otherwise你會得到NPE。嘗試放置TextView ID爲textView1activity_sem_selection佈局。否則,您可以刪除那些分配和參考TextView T,並將其放置在fragment's onCreateView(...)中。

+0

謝謝:)它的工作! –