Android 在片段类中创建私有按钮
我想在我的类的顶部创建我的按钮,但是 findViewById未知,我需要更改什么Android 在片段类中创建私有按钮,android,button,Android,Button,我想在我的类的顶部创建我的按钮,但是 findViewById未知,我需要更改什么 public static class PlaceholderFragment extends Fragment { private Button btn_q_c_1 = (Button)findViewById(R.id.btn_q_c_1); public PlaceholderFragment() { } @Override public View onCrea
public static class PlaceholderFragment extends Fragment {
private Button btn_q_c_1 = (Button)findViewById(R.id.btn_q_c_1);
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_app_launch, container, false);
Toast.makeText(getActivity(), "TEST", Toast.LENGTH_LONG).show();
return rootView;
}
}
改为
private Button btn_q_c_1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_app_launch, container, false);
btn_q_c_1 = (Button)rootview.findViewById(R.id.btn_q_c_1);
Toast.makeText(getActivity(), "TEST", Toast.LENGTH_LONG).show();
return rootView;
}
假设按钮属于fragment\u app\u launch.xml
,则展开布局,需要在当前视图层次结构中查找视图
公共最终视图findViewById(内部id)
在API级别1中添加
查找具有给定id的子视图。如果
视图具有给定id,请返回此视图
参数id要搜索的id
返回层次结构中具有给定id或null的视图
或在创建的活动中使用
btn_q_c_1 = (Button)getView().findViewById(R.id.btn_q_c_1);
谢谢这很有效。你能帮我解释一下findViewById是什么吗?它是View类的一个方法吗?这就是为什么我必须使用rootView.findViewById()?@user3385402@user3385402是的,这是一个视图类的方法,你膨胀了布局,视图属于膨胀的布局,因此
rootView.findViewById(intparam)
嘿,你似乎很有经验。您知道我是否可以通过单击按钮提交捆绑包吗?因此,如果单击按钮1,它会将值为1的int传递给onclicklistener?@Philip use bundle,以便在活动之间传递值。但您不需要仅在同一活动的OnClickListener
中访问它