我正在创建一个带有自定义布局的Dialog Fragment,其中包含一个数字选择器。
为此,我创建了一个DialogFragment类,它实现了NumberPicker.onValueChangeListener和它将使用的布局xml文件。
我遇到一个问题,即将布局中的数字选择器与片段类中的变量相关联,因为'findViewById'“方法无法解析”
如何解决这个问题?
以下代码元素:
对话片段:
public class PlayersDialogueFragment extends DialogFragment implements NumberPicker.OnValueChangeListener {
NumberPicker numberOfPlayersPicker = null;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.players_fragment_layout, null));
numberOfPlayersPicker = (NumberPicker) findViewById(R.id.numberOfPlayersPicker);
numberOfPlayersPicker.setMaxValue(4);
numberOfPlayersPicker.setMinValue(2);
布局 - “players_fragment_layout”:
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/numberOfPlayersPicker"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
我可以在findViewById之前放置getActivity()并运行应用程序,但是这样做会产生一个空对象引用错误。
PS:如果重要,按下按钮时主要活动会调用对话框片段。
答案 0 :(得分:1)
将inflater.inflate(R.layout.players_fragment_layout, null)
分配给变量v
,然后像这样调用v.findViewById
:
public class PlayersDialogueFragment extends DialogFragment implements NumberPicker.OnValueChangeListener {
NumberPicker numberOfPlayersPicker = null;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.players_fragment_layout, null);
builder.setView(v);
numberOfPlayersPicker = (NumberPicker) v.findViewById(R.id.numberOfPlayersPicker);
numberOfPlayersPicker.setMaxValue(4);
numberOfPlayersPicker.setMinValue(2);
}
}