Call of findViewById in Fragment to find a button returns null

前端 未结 4 998
遥遥无期
遥遥无期 2021-01-19 00:54

I´m new to android development and I´m trying to write a small, simple Application. This application should do nothing more than reading the text from 2 EditTexts and when

相关标签:
4条回答
  • 2021-01-19 01:17

    Your button is inside activity_main.xml, but you're inflating R.layout.headline_view:

    this.inflatedView = inflater.inflate(R.layout.headline_view, container, false);
    
    0 讨论(0)
  • 2021-01-19 01:19
    this.inflatedView = inflater.inflate(R.layout.headline_view, container, false);
    
    sendButton = (Button) inflatedView.findViewById(R.id.sendTextButton);
    

    you are looking for a Button with id sendTextButton inside headline_view.xml. But from the layout you posted there is no Button with id sendTextButton. That`s way you get null

    0 讨论(0)
  • 2021-01-19 01:24

    You have to set the onClickListener inside the Activity from which you are managing the fragments and not inside the fragment, if the Button is not in the layout that your fragment is inflating.

    0 讨论(0)
  • 2021-01-19 01:29

    That's the problem

    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String headline = ((EditText) v.findViewById(R.id.enterHeadlineText)).getText().toString();
            ((TextView) v.findViewById(R.layout.headline_view)).setText(headline);
        }
    });
    

    the View v is the view clicked, so of coure v.findViewById() doesn't work..
    to achieve your target you can declare youre EditText and TextView global, in onCreate() use the inflater to instantiate them and onClick method you can use them!

    0 讨论(0)
提交回复
热议问题