我正在使用具有 MyAdapter 的 Fragment Activity 开发 Android 项目:
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
@Override
public int getCount() {
return ITEMS;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - Pokazuje listę
return ImageFragment.init(position);
//return TruitonListFragment.init(position);
case 1: // Fragment # 1 - Pokazuje wybór
return ImageFragment.init(position);
default:
return ImageFragment.init(position);
}
}
}
现在我有扩展片段的 ImageFragment 类。我正在尝试将 ImageFragment 中的 addView() 添加到布局中的元素,并且我有 NullPointerException。它在 Activity 中有效,但在 Fragment 中无效。有可能解决这个问题,到底发生了什么?
public class ImageFragment extends Fragment implements OnClickListener {
int fragVal;
public static ImageFragment init(int val) {
ImageFragment truitonFrag = new ImageFragment();
// Supply val input as an argument.
Bundle args = new Bundle();
args.putInt("val", val);
truitonFrag.setArguments(args);
return truitonFrag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InitializeDatabase(); // Wczytanie zasobów
fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
//
AddonsList = new ArrayList<myAddons>();
//
Parent = new ArrayList<Long>();
Parent.add((long) 0);
GenerateNodeTree((long) 0); // Ustawienie fragmentu na początek
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.fragment_pager_list,
container, false);
linearLayout = new LinearLayout(getActivity());
linearLayout = (LinearLayout) layoutView.findViewById(R.id.Groups);
linearLayout = new LinearLayout(getActivity());
GoTop = (Button) layoutView.findViewById(R.id.Button02);
GoHome = (Button) layoutView.findViewById(R.id.Button01);
return layoutView;
}
private void GenerateNodeTree(Long TreeNode) {
try {
currentProductList = new ArrayList<Products>();
ClearView();
for(ProductGroups grupa : myGroupList) {
Log.i("mm",grupa.getNazwa());
LinearLayout row = new LinearLayout(getActivity());
row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
if(grupa.getPARENTID() == TreeNode & grupa.getPOSPRODID() == 0) { // Przyciski kategorii
ImageButton imgTag = new ImageButton(getActivity());
Button btnTag = new Button(getActivity());
int k = R.drawable.icon_empt;
imgTag.setImageResource(k);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
btnTag.setText(grupa.getNazwa());
btnTag.setId((int) grupa.getPOSPRODGRPID());
btnTag.setOnClickListener(this);
row.addView(imgTag);
row.addView(btnTag);
linearLayout.addView(row); // HERE NULL POINTER APPEARS
}
}
}
catch(Exception exc)
{
//Print.StandardToast(getActivity(), exc.getStackTrace().toString());
}
// Koniec generowania widoku
}
}