我正在尝试使用片段来构建我的第一个正确的Android应用程序.我有一个主要的xml.它由两个垂直片段组成,顶部片段只包含两个TextView.第一个包含静态文本,第二个包含一个值,我最终将从SQL动态获取.
如果我把它作为我的MainActivity.java,那么它很高兴在我的第一个片段中更新TextView的值:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set the Text to try this out
TextView t = (TextView)findViewById(R.id.viewItem);
t.setText("Text to Display");
}
Run Code Online (Sandbox Code Playgroud)
我有两个片段XML和一个java来支持每个,所以我想把这个字段的设置放到支持片段的Java而不是MainActivity的java.
当我把它放在片段中它看起来像这样: -
public class FragmentMainTop extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState){
// -- inflate the layout for this fragment
return inflater.inflate(R.layout.fragmentmt, container,false);
// Set the Text to try this out
TextView t = (TextView)findViewById(R.id.viewItem);
t.setText("Text to Display");
}
Run Code Online (Sandbox Code Playgroud)
但是如果我这样做,我会在TextView行上出错:
"对于FragmentMainTop类型,方法findViewById(int)是未定义的"
那么为什么它不知道这种方法呢?我有ctl/shift/o所以我知道我有所有正确的进口.我不想最终将所有代码放在MainActivity中,因为如果我想在另一个活动中使用Fragment,我将不得不重复所有代码.
我有一个片段,由一个微调器和一个按钮组成.您可以使用微调器选择四个选项之一,然后按钮将转到下一个活动.
为了实现微调器,我需要在Fragment上实现onItemSelectedListener,但是要使用我需要实现onClickListener的按钮.但我不能两个都做?我本以为这是一个非常简单的事情,并且在View上需要多个不同的事件监听器必须是常见的,那么如何实现呢?
这是我正在使用的代码: -
public class FragmentTypeSelect extends Fragment实现OnItemSelectedListener {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState){
// set the view so that it can be referenced
View theView = inflater.inflate(R.layout.fragment_type_select,
container,false);
// set OnClickListener for the button
setUpClickListener(theView,R.id.but_select);
//===============================
// NEW TYPE SPINNER
//===============================
Spinner spinner = (Spinner) theView.findViewById(R.id.new_type_spinner);
spinner.setOnItemSelectedListener((OnItemSelectedListener) this);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.types_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when …Run Code Online (Sandbox Code Playgroud)