简体   繁体   中英

How I can use my edittext in a fragment?

I want editText in the second fragment that has a onClickListener for other operations, like a dialog task.

But my program crashes when I setListener on the EditText or also on the Button.

The exception is: NullPointerExceptions
It's possible that it can't see the layout??? If yes, why?

I have 3 tabs layout and 1 layout like Pager, I do this operations in the activity of the pager.

'name' is my editText

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        Bundle args = getArguments();
        int position = args.getInt(ARG_OBJECT);

        int tabLayout = 0;
        switch (position) {
        case 0:
            tabLayout = R.layout.priority_fields;
            break;
        case 1:
            tabLayout = R.layout.authors_fields;
            name.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub  
                    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(FILL_PARENT, WRAP_CONTENT);
                    ll.setLayoutParams(params);
                    ll.addView(name);
                    ll.addView(surname);
                    authors.addView(ll);
                }
            });
            break;

在此处输入图片说明

the problem is that you arent accessing the EditText the way you do. So you get a NPE here because the app is looking at the wrong resources.

I normally keep a reference to my View inside a fragment, so i always can access the correct widgets:

private View mContentView = null;

public View onCreateView {
    LayoutInflater inflater = getActivity().getLayoutInflater();
    mContentView = inflater.inflate(R.layout.dialog_disclaimer, null);
    builder.setView(mContentView);
}

now when i want to use the EditText somewhere else in the fragment, it can be done like this:

@Override
public void onActivityCreated(Bundle arg0) {
    super.onActivityCreated(arg0);

    bAccept = (Button) mContentView.findViewById(R.id.accept_disclaimer);
    etName = (EditText) mContentView.findViewById(R.id.name);

    bAccept.setOnClickListener(this);
    etName.setOnClickListener(this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM