2014-07-25 33 views
-3

我嘗試在一個Fragment中以編程方式設置TextView的文本。 爲類的代碼如下:Android TextView setText結果爲空文本

public abstract class AbstractFragment extends Fragment 
{ 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) 
    { 
     this.setFileName(); 
    } 

    protected abstract void setFileName(); 
} 

public class ImplementingFragment extends AbstractFragment 
{ 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) 
    { 
     View fragment = inflater.inflate(
       R.layout.fragment_layout, container, false); 

     return fragment; 
    } 

    @Override 
    protected void setFileName() 
    { 
     String fileName = "Test.txt"; 

     TextView textView = ((TextView) getActivity().findViewById(
       R.id.text_file_name)); 
     textView.setText(fileName); 
    } 
} 

佈局如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" > 

    <TextView 
     android:id="@+id/text_pdf_filename_title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/text_pdf_filename" 
     android:textAppearance="?android:attr/textAppearanceMedium" /> 

    <TextView 
     android:id="@+id/text_pdf_file_name" 
     android:layout_marginLeft="15dp" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 
</LinearLayout> 

奇怪的是:一個片段中它的工作原理,在其他它沒有(同一母公司活動)。另一個事實是,我設置文本後,我通過textView.getText()獲取它。如果我嘗試在後面的代碼中獲取文本,我只會得到一個空字符串。另外,如果我調試代碼,我會在文本消失之前看到文本視圖毫秒。

有沒有人有解決方案如何解決該行爲?

+2

是什麼'fileName'?在settign之前將fileName的值記錄到textview和chekc – Raghunandan

+0

@Raghunandan:fileName的值是一個字符串。它不是空的(我檢查)。 –

+0

fileName不爲空,那麼textView必須爲null,從而導致'NullPointerExcpetion'。注意:setText可以爲null – Raghunandan

回答

-1

內部片段使用:

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

    TextView textView = ((TextView) rootView.findViewById(
      R.id.text_file_name)); 
    textView.setText(fileName); 

    return rootView; 
} 
+0

片段是以正確的方式膨脹的。我得到TextView洞察我的方法。具有相同父項的另一個視圖確實可行 –

+0

@der_chirurg你需要發佈更多的代碼。文本視圖所屬的佈局和相關的片段代碼。它很難說現在發生什麼 – Raghunandan

+0

@der_chirurg通過您可以從片段到活動進行通信的方式,並使用界面作爲回調在活動本身中設置文本 – Raghunandan