2013-05-14 140 views
2

我跟着这个人的tutorial如何制作一个ActionBar。比方说,我想改变其中一个片段的TextView。所以我在我的StartActivity.java上添加了onCreate:更改片段内的TextView

TextView textview = (TextView) findViewById(R.id.textView1); 
textview.setText("HI!"); 

当我启动我的应用程序时,它崩溃了。有人能指出我正确的方向吗?

我希望有人花时间看这个家伙的教程,因为他的布局与我的布局基本相同。谢谢。

+2

什么是崩溃?显示logcat .. – Renjith 2013-05-14 09:04:12

+0

@Mnemone发布引发异常的代码部分。 – TheFlash 2013-05-14 09:07:16

+0

你在哪里使用setText()... plz指出..在代码 – Sam 2013-05-14 09:09:30

回答

8

如果你想改变你的组成部分,我建议你做这样的片段中的方法:

import android.os.Bundle; 
    import android.support.v4.app.Fragment; 
    import android.view.LayoutInflater; 
    import android.view.View; 
    import android.view.ViewGroup; 
    import android.widget.TextView; 

    public class DetailFragment extends Fragment { 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
      View view = inflater.inflate(R.layout.details, container, false); 
      return view; 
     } 


     public void setText(String text){ 
      TextView textView = (TextView) getView().findViewById(R.id.detailsText); 
      textView.setText(text); 
     } 

    } 
+0

这样做了;谢谢。 – Mnemone 2013-05-14 09:34:35

+0

getView()始终为空 – Randy 2015-04-27 14:48:46

+0

如何从'MainActivity'访问它 – Si8 2016-10-02 18:26:18

2

你能不能尝试更换getView()与getActivity()?

public void setText(String text){ 
     TextView textView = (TextView) getActivity().findViewById(R.id.detailsText); 
     textView.setText(text); 
    } 
0

我找到了答案here,并Stack overflow

它采用充气:(对我来说它的工作)


public class MyFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View inf = inflater.inflate(R.layout.fragment_place, container, false); 
     TextView tv = (TextView) inf.findViewById(R.id.textview); 
     tv.setText("New text"); 
     return inf; 
    } 
}