java - 单击 ListView 中的按钮不起作用

标签 java android

据了解,类似的案例已被报道,并且该主题有很多答案,但不幸的是,任何事情都适用于我的案例。 这是我的 Activity 代码:

listViewOfReastaurants = findViewById(R.id.listViewOfSensors);
        listViewOfReastaurants.setDividerHeight(10);
        listOfRestaurants = new ArrayList<>();
        adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.list_button, listOfRestaurants);
        listViewOfReastaurants.setAdapter(adapter);

        listViewOfReastaurants.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
                        Toast.LENGTH_LONG).show();
                Intent myIntent = new Intent(getApplicationContext(),
                        DishOfTheDay.class);
                startActivity(myIntent);
            }
        });

这是我的布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">

<ListView
    android:id="@+id/listViewOfSensors"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/textView"
    android:layout_centerHorizontal="true" />

和行模板:

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Row"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:textSize="15sp"
android:padding="20dp"
android:focusable="false">

不幸的是点击按钮没有任何效果。我尝试设置可聚焦等参数,但没有任何帮助。

最佳答案

我认为通过使用类的上下文,您可以在 Activity 之间切换。

尝试类似:

  listViewOfReastaurants.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
                        Toast.LENGTH_LONG).show();
                Intent myIntent = new Intent(getApplicationContext(),
                        DishOfTheDay.class);
                Context context=getBaseContext();
                context.startActivity(myIntent);
            }
        });

我希望这篇文章会对您有所帮助。

关于java - 单击 ListView 中的按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50202204/

相关文章:

java - Java 代码如何检查浮点寄存器的数量?

java - 填充多维数组时 IndexOutOfBounds 异常

android - 操作栏一直隐藏

android - 如何删除android中的内部存储文件?

java - 有没有Java Android代码可以从USB端口的数据线输出短脉冲?

Android - 向服务器发送 2 个文件

android - 如何为图像的某些像素设置颜色

java - 在SQL中对相关表使用批量插入

java - 在为 GenerationType.IDENTITY 提供标识符值作为生成标识符的策略时传递给持久化的分离实体

java - 找到异常调用者并修改以显示值