0

我试图在我的 BottomSheet 对话框中返回一个微调器值。但它总是返回 NullPointerException。下面是我的 String.XML 文件

 <string-array name="e_type">
    <item>item1</item>
    <item>item2</item>
</string-array>

这是我的 bottomsheet_activity.xml 文件

  <Spinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/e_type" />

我正在尝试通过以下代码获取价值

final BottomSheetDialog dialog3 = new BottomSheetDialog(MainActivity.this);
dialog3.setContentView(R.layout.bottomsheet_activity);

final Spinner spinner=(Spinner) findViewById(R.id.spinner);
final String itemText = (String) spinner.getSelectedItem();

String requesttype=itemText; //Trying to use this variable but returning null

dialog3.show();

为什么它返回 null ,我不知道

4

3 回答 3

1

您的微调器为空,因为您是从活动的 xml 文件中找到它。试试下面的代码,

final BottomSheetDialog dialog3 = new BottomSheetDialog(MainActivity.this);
View mDialogView = LayoutInflater.from(this).inflate(R.layout.activity_mine, null)
dialog3.setContentView(mDialogView);

final Spinner spinner=(Spinner) mDialogView.findViewById(R.id.spinner);
final String itemText = (String) spinner.getSelectedItem();

String requesttype=itemText; //Trying to use this variable but returning null

dialog3.show();

希望对你有帮助!!

于 2020-02-13T05:13:27.700 回答
0

我希望这对你有用。

String requesttype;

 @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final BottomSheetDialog dialog3 = new BottomSheetDialog(NewActivity.this);
    dialog3.setContentView(R.layout.lay_new);

    final Spinner spinner=(Spinner) dialog3.findViewById(R.id.spinner);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            requesttype=parent.getItemAtPosition(position).toString();
            Log.e("requesttype",requesttype);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    dialog3.show();
}
于 2020-02-13T05:13:45.530 回答
0

您正在从

final BottomSheetDialog dialog3 = new BottomSheetDialog(MainActivity.this);
dialog3.setContentView(R.layout.bottomsheet_activity);

所以改变这个-:

final Spinner spinner=(Spinner) findViewById(R.id.spinner);
final String itemText = (String) spinner.getSelectedItem();

到-:

final Spinner spinner=(Spinner) dialog3.findViewById(R.id.spinner);
final String itemText = (String) spinner.getSelectedItem();
于 2020-02-13T06:18:09.393 回答