如何在Fragment中使用findViewById
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                如何在Fragment中使用findViewById
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                findViewById方法卻只能被用在Activity類中,如果想在fragment中使用,
需要在findViewById前面 添加getView();
下面是一段代碼,
public class SquareFragment extends Fragment {private TextView sq; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {View square = inflater.inflate(R.layout.square_layout, container, false); sq =getView().findViewById(R.id.square); sq.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View view) {MainActivity ma = (MainActivity) getActivity(); ma.setTabSelection(2); }}); return square; } }
這樣用getView()前面沒有問題,但是運行會發(fā)現(xiàn)空指針異常,原因呢是在使用了onCreateView創(chuàng)建視圖, inflater插入的布局,用getView()引用,不是識別是哪一個布局
所以就報了空指針,
正確的寫法如下
public class SquareFragment extends Fragment {private TextView sq; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {View square = inflater.inflate(R.layout.square_layout, container, false); sq = square.findViewById(R.id.square); sq.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View view) {MainActivity ma = (MainActivity) getActivity(); ma.setTabSelection(2); }}); return square; } }
在findViewById前面添加 插入的那個布局,它就能識別是哪一個布局了。
 
 
 
總結(jié)
以上是生活随笔為你收集整理的如何在Fragment中使用findViewById的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 求壤字开头的成语接龙!
- 下一篇: 电视剧《暗香》的内容是?
