【问题标题】:Fragment to context?片段到上下文?
【发布时间】:2013-06-23 06:53:07
【问题描述】:
   listClass.add(new ListClass(json.getString("ProductId"), json
                            .getString("ProductPrice")));
            }
        list.setAdapter(new MyListAdapter(Fragment1.this, listClass));

但是在课堂上:MyListAdapter 我收到一个错误:

public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = LayoutInflater.from(fragment).inflate(
            R.layout.pricelist, parent, false);

fragment1 类扩展了片段。 而在rowView = layoutinflater.from(//我这里只能扩展上下文 而不是片段)。 我该怎么办??

更新 mylistadapter 类:

public class MyListAdapter extends BaseAdapter {

    private Fragment fragment;
    private ArrayList<ListClass> listClass = new ArrayList<ListClass>();

    public MyListAdapter(Fragment1 fragment1, ArrayList<ListClass> listClass1) {
        this.fragment = fragment1;
        this.listclass = listClass1;
    }

    @Override
    public int getCount() {
        return listClass.size();
    }

    @Override
    public Object getItem(int position) {
        return ListClass.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = LayoutInflater.from(fragment).inflate(
                R.layout.pricelist, parent, false);

        TextView text1 = (TextView) rowView.findViewById(R.id.title);
        TextView text2 = (TextView) rowView.findViewById(R.id.details);
        text1.setText(BeanClass.get(position).phoneName);
        text2.setText(BeanClass.get(position).phonePrice);
        return rowView;
    }

}

【问题讨论】:

  • 使用这个list.setAdapter(new MyListAdapter(getActivity(), listClass))
  • 对不起,我输入了错误的名字。修复它(我仍然收到错误)。
  • 你在哪里初始化LayoutInflater?。您是否将活动上下文传递给 MyListAdapter 的构造函数并使用相同的?
  • 我没有初始化它..

标签: android android-fragments android-context


【解决方案1】:

要获取活动的上下文,请使用getActvitiy()

http://developer.android.com/reference/android/app/Fragment.html#getActivity()

public final Activity getActivity ()

返回此片段当前关联的 Activity。

  list.setAdapter(new MyListAdapter(getActivity(), listClass));

然后在你的 MyListAdapter 构造函数中

    Context mContext; // you can remove this
    LayoutInflater mInflater; 
    private ArrayList<ListClass> listClass = new ArrayList<ListClass>(); 
    public MyListAdapter(Context context, ArrayList<ListClass> listClass1)
    {
    mContext = context; // you can remove this
    mInflater = LayoutInflater.from(mContext); // get rid of this statement 
    mInflater = LayoutInflater.from(context); // you can directly use context
    this.listclass = listClass1;
    }

然后在getView

    View rowView = mInflater.inflate(
        R.layout.pricelist, parent, false); 

【讨论】:

  • 非常感谢您解决了我的问题
  • @KingOmar 嗯。我很高兴这是错误的点击因为我认为答案是正确的。
猜你喜欢
  • 2021-09-28
  • 2016-10-19
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 2020-07-10
  • 2015-04-24
  • 2013-10-24
相关资源
最近更新 更多