My FragmentActivity循环并创建大量片段,每个片段都带有`new TextView。在一些帮助之后,我有了这个:
FragmentActivity.java
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
for (int j=0; j<positionsCount; j++) {
...
mTabsAdapter = new PositionFragmentAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText("My Tab Name"), Fragment.class, args);
}
}
Fragment.java
public class Fragment extends Fragment {
private static int id = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout mLinearLayout = new LinearLayout(getActivity());
TextView mTextView = new TextView(getActivity());
mTextView.setId(id);
id++;
mLinearLayout.addView(mTextView);
return mLinearLayout;
}
@Override
public void onStart() {
super.onStart();
Bundle args = getArguments();
id.setText(args.get("posName").toString()); // ERROR HERE: "Cannot invoke setText(String) from primitive type int"
}
}
如何停止错误?
编辑2:
06-11 12:54:53.843: E/AndroidRuntime(21005): java.lang.NullPointerException
06-11 12:54:53.843: E/AndroidRuntime(21005): at com.example.guide.Fragment.onStart(Fragment.java:33)
06-11 12:54:53.843: E/AndroidRuntime(21005): at android.support.v4.app.Fragment.performStart(Fragment.java:1484)
...
答案 0 :(得分:0)
您在整数上调用setText,而不是TextView。而不是这个
id.setText(args.get("posName").toString());
这样做:
mTextView.setText(args.get("posName").toString());
请注意,您必须使TextView成为Fragment的实例变量,以便可以从其他方法访问它。
public class Fragment extends Fragment {
TextView mTextView;