我的var obj = localStorage.getItem('obj');
if(obj !== null)
{
....
//show the obj in label or do what you want with it
...
}
出现错误,这是我的代码,错误指向此代码,其错误指向Adapter
,它说:
错误:类型不兼容:HomeFragment无法转换为上下文
HomeFragment.java
这是我的 HomeFragment.java
adapter = new Adapter(models,this);
然后是我的 Adapter.java
public class HomeFragment extends Fragment {
//cardview
ViewPager viewPager;
Adapter adapter;
List<Model> models;
Integer[]colors = null;
ArgbEvaluator argbEvaluator = new ArgbEvaluator();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home,container,false);
//cardview
models = new ArrayList<>();
models.add(new Model(R.drawable.brochure,"Brochure","Lorem ipsum dolor sit amet"));
models.add(new Model(R.drawable.sticker,"Sticker","Lorem ipsum dolor sit amet"));
models.add(new Model(R.drawable.poster,"Poster","Lorem ipsum dolor sit amet"));
models.add(new Model(R.drawable.namecard,"Name Card","Lorem ipsum dolor sit amet"));
adapter = new Adapter(models,this);
viewPager = getView().findViewById(R.id.viewPager);
viewPager.setAdapter(adapter);
viewPager.setPadding(130,0,130,0);
}
}
答案 0 :(得分:2)
更改此:
adapter = new Adapter(models,this);
对此:
adapter = new Adapter(models, (Context) getActivity());
您必须通过Context
。并且Activity
可以强制转换为Context
,而Fragment
不能强制转换。
因此,您必须检索Activity
正在执行的当前getActivity()
的实例。
如果您想在Adapter
中创建Activity
的实例,则可以通过简单地传递this
来实现,就像我之前说过的,强制转换Activity
-可以Context
,但不能Fragment
。因此Activity
将被强制转换为Context
,但是当您想在Fragment
中创建相同内容时,就不能简单地传递this
,从而引发错误。 / p>
正如您在评论中所说,现在还有另一个错误,这是因为您已经在该方法的第一行return
处获得了某些内容,因此,该行下的每一行将永远无法到达,这就是为什么出现该错误,请放置此行
return inflater.inflate(R.layout.fragment_home,container,false);
最后,错误将消失。
在您的方法中进行了更多编辑之后,您的OnCreateView
将看起来像这样:
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home, container, false); // Created a instance of View which we can return later.
//cardview
models = new ArrayList<>();
models.add(new Model(R.drawable.brochure,"Brochure","Lorem ipsum dolor sit amet"));
models.add(new Model(R.drawable.sticker,"Sticker","Lorem ipsum dolor sit amet"));
models.add(new Model(R.drawable.poster,"Poster","Lorem ipsum dolor sit amet"));
models.add(new Model(R.drawable.namecard,"Name Card","Lorem ipsum dolor sit amet"));
adapter = new Adapter(models,this);
viewPager = view.findViewById(R.id.viewPager); // Change getView() to view here.
viewPager.setAdapter(adapter);
viewPager.setPadding(130,0,130,0);
return view; // Returned the view.
}
答案 1 :(得分:0)
使用this
代替getActivity()
更改此
adapter = new Adapter(models,this);
到
adapter = new Adapter(models,getActivity());