简体   繁体   English

如何在片段中使用我的edittext?

[英]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. 我想editText在具有第二个片段onClickListener其他操作,如一个对话框任务。

But my program crashes when I setListener on the EditText or also on the Button. 但是,当我在EditText或Button上设置setListener时,程序崩溃。

The exception is: NullPointerExceptions 例外是: 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. 我有3个选项卡布局和1个类似分页器的布局,我在分页器的活动中执行此操作。

'name' is my editText '名字'是我的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. 问题是您无法以您的方式访问EditText。 So you get a NPE here because the app is looking at the wrong resources. 因此,您在这里得到了NPE,因为该应用正在寻找错误的资源。

I normally keep a reference to my View inside a fragment, so i always can access the correct widgets: 我通常在片段中保留对View的引用,因此我始终可以访问正确的小部件:

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: 现在,当我想在片段中的其他位置使用EditText时,可以这样进行:

@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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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