在片段中添加按钮?
在片段中添加按钮?
这个问题已经在这里有了答案:
我正在尝试向我的fragment布局中添加一个按钮,但它说方法findViewByid
无法解析。我正在片段的onCreateView
方法中实现它。为什么会给我这个错误?
import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.ViewGroup; import android.view.View; import android.widget.Button; public class extra extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment Button myButton = (Button) findViewById(R.id.my_button); return inflater.inflate(R.layout.extra, container, false); } }
admin 更改状态以发布 2023年5月20日
public class extra extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = LayoutInflater.from(getActivity()).inflate( R.layout.YOUR_LAYOUT, null); Button myButton = (Button) v.findViewById(R.id.my_button); return v; }}
使用以上代码
你需要使用View
。例如,
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.extra, container, false); // Inflate the layout for this fragment Button myButton = (Button) rootView.findViewById(R.id.my_button); return rootView; }