2016-05-10 62 views
-1

TextView.setText在函數調用中不起作用。我在一個方法中傳遞數據(「changeText」)。該代碼不起作用。應用停止工作。當我試圖改變文本onActivityCreated它的工作原理,但是當我在一個函數TextView setText方法不能在片段中工作

public class Fragment_b extends Fragment { 

TextView tv; 
@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    return inflater.inflate(R.layout.fragment_b, container, false); 
} 

@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 
    tv = (TextView) getActivity().findViewById(R.id.textView); 
    changeText(90); 
} 
public void changeText(int data) 
{ 
    tv = (TextView) getActivity().findViewById(R.id.textView); 
    tv.setText(String.valueOf(data)); 
} 
} 
+1

當你說應用程序停止工作,是一個異常拋出?在調試代碼時,你是否驗證了'tv'是一個有效的對象? –

+0

發佈您的位置.... –

回答

0

傳遞數據,它不工作,首先宣佈你MAINVIEW全球。然後用那個來尋找你的視圖,調用getActivty()。findViewById ...沒有使用與你相同的佈局。

private View rootView; 

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

rootView = inflater.inflate(R.layout.fragment_b, container, false); 
    return rootView; 
} 

然後

tv = (TextView) rootView.findViewById(R.id.textView); 
0
public class Fragment_b extends Fragment { 

     TextView tv; 
     @Nullable 
     @Override 



     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle  savedInstanceState) { 
       View v = inflater.inflate(R.layout.fragment_b, container, false); 
tv = (TextView)v.findViewById(R.id.textView); 
return v; 
      } 

     @Override 
     public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 

     changeText(90,tv); 
     } 
     public void changeText(int data,TextView tv) 
     { 
     tv.setText(String.valueOf(data)); 
     } 
    } 
0
getActivity().runOnUiThread(new Runnable() 
    { 
     @Override 
     public void run() 
     { 
      changeText(90); 
     } 
    });