您好我正在使用android.I曾尝试将布局扩展到片段中,但它在代码中显示错误“方法getLayoutInflater()未定义为类”。如何在片段中访问布局?请帮帮我,我是android的新手。谢谢
这是我的代码
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
答案 0 :(得分:8)
getLayoutInflater()
是Context
使用getActivity().getLayoutInflater()
...在onAttach()
Fragment
回拨后有效
答案 1 :(得分:1)
我假设你在一个Activity中调用它。尝试做
LayoutInflater li = (LayoutInflater) getApplicationContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View header = li.inflate(R.layout.listview_header_row, null);
另一方面,如果您是从自定义适配器调用它,则需要将LayoutInflater或Context变量传递给适配器。
适配器:
class MyCustomAdapter{
LayoutInflater li;
public MyCustomAdapter (LayoutInflater li) {
layoutInflater = li;
}
//...
}
的活动:
public class MyActivity extends Activity {
//...
public void onCreate() {
MyCustomAdapter adapter = new MyCustomAdapter((LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
listView.setAdapter(myCustomAdapter);
}
//...
}
答案 2 :(得分:0)
试试这个:
View view = LayoutInflater.from(getActivity()).inflate(
R.layout.your_layout, null);
完整代码
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = LayoutInflater.from(getActivity()).inflate(
R.layout.your_layout, null);
return view;
}