我想新的文本设置为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”);' –