是在片段或片段活动中启动的 UI 元素



我正在将活动类型的应用程序移植到片段类型的应用程序。我有点困惑我应该在哪里启动片段的 UI 元素。

例如,如果我从类中的Fragment类启动按钮FragmentActivity不会收到任何错误

    btnOne = (Button) findViewById(R.id.btn_one);

但是,如果我尝试启动onClick侦听器,则会出现类型为java.lang.NullPointerException的错误。

再说一次,我在Fragment类中找不到方法findViewById

我真的被迫在FragmentActivity中启动并在Fragment中指定听众吗?

您通常会在片段中启动按钮。一个例子是:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View fragmentView = inflater.inflate(R.layout.yourlayout, container, false);
        Button yourbutton = (Button) fragmentView.findViewById(R.id.button);
        yourbutton.setOnClickListener(new View.OnClickListener(){
               @Override
               public void onClick(View v) {
                     //Do your thing
               }
        }
        return fragmentView;
}

最新更新