我嘗試在一個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()獲取它。如果我嘗試在後面的代碼中獲取文本,我只會得到一個空字符串。另外,如果我調試代碼,我會在文本消失之前看到文本視圖毫秒。
有沒有人有解決方案如何解決該行爲?
是什麼'fileName'?在settign之前將fileName的值記錄到textview和chekc – Raghunandan
@Raghunandan:fileName的值是一個字符串。它不是空的(我檢查)。 –
fileName不爲空,那麼textView必須爲null,從而導致'NullPointerExcpetion'。注意:setText可以爲null – Raghunandan