簡體   English   中英

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

[英]How I can use my edittext in a fragment?

我想editText在具有第二個片段onClickListener其他操作,如一個對話框任務。

但是,當我在EditText或Button上設置setListener時,程序崩潰。

例外是: NullPointerExceptions
有可能看不到布局??? 如果是,為什么?

我有3個選項卡布局和1個類似分頁器的布局,我在分頁器的活動中執行此操作。

'名字'是我的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;

在此處輸入圖片說明

問題是您無法以您的方式訪問EditText。 因此,您在這里得到了NPE,因為該應用正在尋找錯誤的資源。

我通常在片段中保留對View的引用,因此我始終可以訪問正確的小部件:

private View mContentView = null;

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

現在,當我想在片段中的其他位置使用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