【问题标题】:Why do I get expression expected fab.setOnClickListener(View?为什么我得到表达式预期 fab.setOnClickListener(View?
【发布时间】:2018-11-14 14:39:17
【问题描述】:

为什么我不能在fab.setOnClickListener(ViewonCreate 方法中创建弹出对话框?

是因为语法吗?我缺少表达吗? 我的代码是否已经过时了,因为我的导师是一门古老的 udemy 课程?

      public class MainActivity extends AppCompatActivity {

        private AlertDialog.Builder dialogBuilder;
        private AlertDialog dialog;
        private EditText groceryItem;
        private EditText getGroceryItem;
        private EditText quantity;
        private Button saveButton;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            FloatingActionButton fab = findViewById(R.id.fab);
       // === error appears on the next line ===
            fab.setOnClickListener(View,  

            createPopupDialog());

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }


         private void createPopupDialog() {

            dialogBuilder = new AlertDialog.Builder(this);
            View view = getLayoutInflater().inflate(R.layout.popup, null);
            groceryItem = view.findViewById(R.id.groceryItem);
            quantity = view.findViewById(groceryQty);
            saveButton = view.findViewById(R.id.saveButton);

            dialogBuilder.setView(view);
            dialog = dialogBuilder.create();
            dialog.show();



        }


    }

【问题讨论】:

  • 什么是View 作为参数传递? setOnClickListener 在这里期待什么?

标签: java android xml android-layout


【解决方案1】:

您没有在setOnClickListener() 中传递正确的参数。
像这样创建监听器:

fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        createPopupDialog();
    }
});

【讨论】:

    【解决方案2】:

    我认为您想使用 lambda 表达式。如果是这种情况,这是正确的语法:

    fab.setOnClickListener((View v) -> {
        createPopupDialog();
    });
    

    【讨论】:

      猜你喜欢
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多