我试图以编程方式在单击项目后将TextView添加到片段。但是,当我尝试我的代码时,它会抛出NullPointerException。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
mAddTextView = (TextView)view.findViewById(R.id.text_view);
mAddTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout thisRelativeLayout = (RelativeLayout)getActivity().findViewById(R.id.fragment_relative_layout);
TextView random = new TextView(getActivity());
random.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
random.setText("New Text Box");
createSingleEventThis.addView(
random
);
}
});