FindViewById在片段中
我正在使用片段和naviagaton抽屉活动的应用程序中工作。 我做了一些基本的事情,我经常不得不写“findViewById”。FindViewById在片段中
spinner = (Spinner)findViewById(R.id.spinner);
通常它工作正常,但在onCreatView的片段我有麻烦。程序中的任何地方都会显示“无法解析方法findviewbyid”,我在这里使用findviewbyId。
我读了很多的问题和答案,这个问题并试图东西展现出来:
1.
spinner = (Spinner)getView.findViewById(R.id.spinner);
return inflater.inflate(R.layout.fragment_first, container, false);
2.
spinner = (Spinner)getActivity.findViewById(R.id.spinner);
return inflater.inflate(R.layout.fragment_first, container, false);
3.
View v = inflater.inflate(R.layout.fragment_first, container, false);
spinner = (Spinner)v.findViewById(R.id.spinner);
return v;
但没有任何帮助解决我的问题......
完整代码:
public class First extends Fragment {
Spinner spinner;
public First() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
spinner = (Spinner)findViewById(R.id.spinner);
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
那么,如何可以使用textviews,imageviews,微调等的片段???
编辑: 我做了一个新的简单的项目,知道我可以用按钮的工作,TextView的......,但我不知道这是否是正常的碎片得到警告,同时初始化对象:
textView=(TextView)v.findViewById(R.id.textView);
当我用我的鼠标(TextView)我得到这个报告:
Casting 'v.findViewById(R.id.textView)' to 'TextView' is redundant
这好吗?我该如何解决这个问题?
这应该解决如下问题 修改onCreateView()
:
View view = inflater.inflate(R.layout.fragment_first, container, false);
spinner = (Spinner)view.findViewById(R.id.spinner);
return view;
注意布局fragment_first
应该在这种情况下,你想找到的意见(即微调)。
试试这个:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
// Defines the xml file for the fragment
View view = inflater.inflate(R.layout.fragment_foo, parent, false);
spinner = (Spinner)view.findViewById(R.id.spinner);
return view;
}
谢谢,但它并没有帮助 – user7940193
这不是你的完整代码。尝试解决方案。 –
这并没有解决我的问题。你最后一句话是什么意思?我需要一个微调和first_fragment xml文件中的微调ID?是的,我有 – user7940193
@ user7940193我的意思是,Spinner对象应该添加到你正在膨胀的XML布局文件中,并且它应该有'spinner',你现在得到了什么错误? 'NullException'或编译错误还是什么? – Yazan
是的,我做到了,但没有奏效。现在我创建了一个新的非常简单的项目,它工作,不知道我做错了什么,但我有其他错误。我将很快将代码添加到问题 – user7940193