片段中的getLayoutInflater()

udi*_*lek 45 android android-fragments

我想表明我的成绩在搜索ListViewFragment,但它失败的:

LayoutInflater inflater = getLayoutInflater();
Run Code Online (Sandbox Code Playgroud)

Fragment类型中的方法getLayoutInflater(Bundle)不适用于参数()

这是我的代码:

public View getView(int position, View convertView, ViewGroup parent)
  {
   LayoutInflater inflater = getLayoutInflater();
   View row;

   row = inflater.inflate(R.layout.list_single, parent, false);

   TextView textview = (TextView) row.findViewById(R.id.TextView01);
   ImageView imageview = (ImageView) row
     .findViewById(R.id.ImageView01);

   textview.setText(data_text[position]);
   imageview.setImageResource(data_image[position]);

   return (row);

  }
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

tyc*_*czj 153

如果你是一个你想要的片段

getActivity().getLayoutInflater();
Run Code Online (Sandbox Code Playgroud)

要么

LayoutInflater.from(getActivity());
Run Code Online (Sandbox Code Playgroud)

你也可以

View.inflate();
Run Code Online (Sandbox Code Playgroud)

要么

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Run Code Online (Sandbox Code Playgroud)

  • 使用getActivity()而不是上下文 (3认同)

小智 5

在 Activity 中,您可以这样使用:

this.getLayoutInflater();
Run Code Online (Sandbox Code Playgroud)

对于 Fragment,您需要将关键字“this”替换为“getActivity()”

getActivity().getLayoutInflater();
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助!