Call of findViewById in Fragment to find a button returns null

那年仲夏 提交于 2019-12-01 18:11:09
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

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!

Tarsem Singh

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!