在onClick()(内部类)中向片段添加TextView

时间:2015-08-25 20:33:19

标签: android android-fragments textview inner-classes

我试图以编程方式在单击项目后将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
            );
        }
    });

0 个答案:

没有答案