logcat说:
尝试调用虚拟方法' ...'在null对象上 参考
当我将一个孩子添加到" root_view"时,我会调用上下文。看起来
getActivity()
无法正常运作。我到处搜索,但我没有找到任何解决方案。也许问题是onAttach
方法?或者我可能需要在MainActivity
和片段之间创建一个类?
这是我的片段代码:
public class Profilo extends Fragment {
private OnFragmentInteractionListener mListener;
public Profilo() {
// Required empty public constructor
}
public static Profilo newInstance(String param1, String param2) {
Profilo fragment = new Profilo();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
ArrayList<String> namesOfNumbers = new ArrayList<String>();
namesOfNumbers.add("uno");
namesOfNumbers.add("due");
namesOfNumbers.add("tre");
namesOfNumbers.add("quattro");
namesOfNumbers.add("cinque");
namesOfNumbers.add("sei");
namesOfNumbers.add("sette");
namesOfNumbers.add("otto");
namesOfNumbers.add("nove");
namesOfNumbers.add("dieci");
LinearLayout root_view = (LinearLayout) getView().findViewById(R.id.linear_layout_main_profilo);
TextView word_view_1 = new TextView(getActivity());
word_view_1.setText(namesOfNumbers.get(0));
root_view.addView(word_view_1);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profilo, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
Toast.makeText(context,"NOTIFICATION FRAGMENT ATTACHED",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
答案 0 :(得分:0)
RETURN
视图; LinearLayout
中致电 TextView
, onCreateView
。尝试
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_profilo, null);
LinearLayout root_view = (LinearLayout) view .findViewById(R.id.linear_layout_main_profilo);
TextView word_view_1 = new TextView(getActivity());
word_view_1.setText(namesOfNumbers.get(0));
root_view.addView(word_view_1);
return view;
}