我想新的文本設置爲TextView
。我在MainActivity
中有TextView
的新值,但此活動不知道此TextView
。 TextView
在文件fragment_main.xml
。片段類包含在類似內部靜態類的MainActivity.java
文件中。它是Eclipse中帶有片段的默認生成活動。你可以幫我嗎?
public class MainActivity extends FragmentActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() { }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
activity_main.xml中
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.zonemedia.skener.MainActivity"
tools:ignore="MergeRootFrame" />
fragment_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/viewmoje"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
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"
tools:context="com.zonemedia.skener.MainActivity$PlaceholderFragment" >
<TextView
android:id="@+id/texturl"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text_url" />
</LinearLayout>
EDIT 1: 我試圖使公共方法(=設定器)的片段,並從FragmentActivity調用它。 我也嘗試直接從片段改變文本: TextView textUrl = (TextView) getView().findViewById(R.id.texturl); textCode.setText("random");
我試過了@ masmic_87寫道。在我定義的片段中 TextView fragmentTextView = (TextView)getView().findViewById(R.id.texturl);
然後在活動中我放了你的代碼。應用程序仍然會崩潰:
java.lang.RuntimeException: Unable to start activity ComponentInfo{.....MainActivity}: java.lang.NullPointerException caused by line 86: ((PlaceholderFragment) fragment).fragmentTextView.setText("something");
最後我直接嘗試調用靜態字符串從靜態的片段,但MainActivity.this是理由強調:靜磁場MainActivity.this應以靜態的方式進行訪問,並沒有外圍實例可以在範圍內訪問MainActivity類型。
我也嘗試將內部類PlaceholderFragment移動到新的.java文件,現在它不是靜態的。我嘗試了從這裏的所有建議,並沒有任何工作
求助 我不知道我的頭在哪裏。在片段我打電話(的TextView)getView() ....代替
View rootView = inflater.inflate(R.layout.fragment_main, container,false);
mTextView = (TextView) rootView.findViewById(R.id.texturl);
mTextView.setText("new text");
你有什麼可讀的嗎? –
你應該在你的活動中引用你的片段。 – Gilson
我試圖在Fragment中創建公共方法(= setter),並從FragmentActivity調用它。我也嘗試直接從片段改變文本: 'TextView textUrl =(TextView)getView()。findViewById(R.id.texturl); \t \t \t textCode.setText(「random」);' –