我有一个扩展Fragment的类。我想添加一个Spinner,但他需要扩展Activity。它能以不同的方式完成吗?
如果我扩展了一个类Activity,但是在这种情况下我不能这样做,以下内容应该有用。
public class Parameters extends Fragment implements AdapterView.OnItemSelectedListener{
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.parameters_tab3, container, false);
return rootView;
spinner = (Spinner) findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this.getContext(), R.array.strength_class_of_concrete, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView myText = (TextView) view;
Toast.makeText(this, "selected" + myText.getText(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kaminski.bartek.columnec2.MainActivity$PlaceholderFragment">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="68dp"
android:id="@+id/spinner" />
</RelativeLayout>
<resources>
<string name="app_name">Column EC2</string>
<string name="action_settings">Settings</string>
<string-array name="strength_class_of_concrete">
<item>C12/15</item>
<item>C16/20</item>
<item>C20/25</item>
<item>C25/30</item>
<item>C30/37</item>
<item>C35/45</item>
<item>C40/50</item>
<item>C45/55</item>
<item>C50/60</item>
<item>C55/67</item>
<item>C60/75</item>
</string-array>
</resources>
答案 0 :(得分:2)
在设置微调器之前退出该函数。设置微调器后写return rootView
。喜欢这个
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.parameters_tab3, container, false);
spinner = (Spinner) rootView.findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this.getContext(), R.array.strength_class_of_concrete, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
return rootView;
}
修改强>
如果您正在处理片段,则view
中的onCreate
会被充气。现在你应该在那个膨胀的视图中找到视图。像
spinner = (Spinner) rootView.findViewById(R.id.spinner);