简体   繁体   English

父活动片段中的EditText的NullPointerException findViewByID

[英]NullPointerException findViewByID of a EditText inside a fragment from his parent activity

I have a problem here, I'm getting a NullPointerException when I try to set text inside an EditText placed in my layout_fragment.xml . 我在这里遇到问题,当我尝试在layout_fragment.xml中放置的EditText内设置文本时,出现NullPointerException

I'm using findViewById(R.id.TextView) on the fragment parent Activity in onCreate() . 我在onCreate()的片段父Activity上使用findViewById(R.id.TextView) onCreate()

The activity has drawer navigation implemented and the layout_fragment.xml belongs to a the first displayed fragment of it. 该活动已实现了抽屉式导航,并且layout_fragment.xml属于该活动的第一个显示片段。

Navigation.class Navigation.class

EditText edt_nome;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.navigation);
    Intent intent = getIntent();
    edt_nome = (EditText)findViewById(R.id.home_nome);
    edt_nome.setText("someText");
}

The code is not much and its simplified because of a confidentiality agreement. 由于保密协议,该代码不多且已简化。

i think you are trying to access activity to early than it is created. 我认为您正在尝试尽早创建活动。

so move this code 所以移动这段代码

    edt_nome = (EditText)findViewById(R.id.home_nome);
edt_nome.setText("someText");

to onActivityCreated,i think that should fix the issue if not please post exception details. 到onActivityCreated,我认为应该解决该问题,否则请发布异常详细信息。

You just cant edit any widget like that. 您只是不能编辑任何这样的小部件。 I suggest to handle with fragments and implement onCreateView() 我建议处理片段并实现onCreateView()

:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        rootView = inflater.inflate(R.layout.FRAGMENT_LAYOUT, container, false);
        EditText et;
        et = (EditText) rootView.findViewById(R.id.EditText);
        et.setText("SomeText");
        (...)
      }

about the previous answer, take a look on this topic: 关于先前的答案,请查看以下主题:

Android Fragment onCreateView vs. onActivityCreated Android片段onCreateView与onActivityCreated

If you have declared <EditText> in layout_fragment.xml then you must use setContentView(R.layout.layout_fragment); 如果在layout_fragment.xml中声明了<EditText> ,则必须使用setContentView(R.layout.layout_fragment); ;。 to deal with that EditText 处理那个EditText

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

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