getLayoutInflater无法解析

时间:2016-03-12 13:21:05

标签: android android-studio

此代码属于我的自定义spinner的arrayadapter。我在getLayoutInflater()方法中遇到无法解析方法的错误,我不知道为什么。 任何帮助将不胜感激。

    public View getCustomView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater= getLayoutInflater();
    View mySpinner = inflater.inflate(R.layout.spinneritems, parent, false);

    TextView main_text = (TextView) mySpinner.findViewById(R.id.spinneritem);
    main_text.setText(spinnerValues[position]);
    return mySpinner;
}

}

3 个答案:

答案 0 :(得分:2)

试试这个

  LayoutInflater inflater= getActivity().getLayoutInflater();

 LayoutInflater inflater= youContext.getLayoutInflater();

因为方法getLayoutInflater()属于Activity,您必须使用getActivity()方法获取它或将上下文传递到adapter构造函数中,例如:

公共类YourAdapter扩展了ArrayAdapter {

    private Context mContext;
    private ArrayList<Strings> someList;

    public YourAdapter (Context context, ArrayList<String> someList) {
        super(context, R.layout.comment_item, someList);
        **this.mContext = context;**
        this.someList = someList;

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) View rowView = convertView;
        if (rowView == null) {
            LayoutInflater inflater = **mContext**.getLayoutInflater();
            rowView = inflater.inflate(R.layout.yourItem, null);

            rowView.setTag(viewHolder);
        }

        return rowView;
    }

}

并在Activity

YourAdapter mAdapter = new YourAdapter ( **getActivity()**,someList);

答案 1 :(得分:2)

  

无法解析getLayoutInflater()

上的方法

Android getLayoutInflater () 检索已连接到当前上下文并为您正在运行的设备正确配置的标准LayoutInflater实例。

在这里,您缺少设置上下文

<强>唐&#39;吨

  LayoutInflater inflater= getLayoutInflater();

<强>不要

LayoutInflater inflater= Your_class_context.getLayoutInflater();

答案 2 :(得分:0)

试试这个对我有用。

// custom hook
export const useSetup() {
  useEffect(() => {
    if (data) fetch().then((data) => dispatch(setInit(data)))
  }, [dispatch])
}


// functional component
export function Details() {
  useSetup()