我正在将活动类型的应用程序移植到片段类型的应用程序。我有点困惑我应该在哪里启动片段的 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;
}