【问题标题】:Button not causing the onClick event按钮不会导致 onClick 事件
【发布时间】:2021-11-11 12:57:39
【问题描述】:

我正在开发一个应用程序(学校项目的一部分),并且我有一个活动,它由一个 ImageView、一个 SearchView、一个 ListView 和一个按钮组成。

我正在尝试将按钮放在 ListView 的前面,该按钮一直在 gucci 工作,直到我真正让按钮发挥作用。 设置 onClick 方法后,我注意到按钮没有做任何事情。我尝试使用按钮打印一些东西,但没有任何效果。还尝试在 ListView 之外创建一个新按钮,但这也失败了(也没有导致 onClick 事件)。

我有点无能为力,想不出任何可能导致此问题的原因...

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/main_color"
    android:orientation="vertical"
    android:divider="@android:color/transparent"
    android:dividerHeight="10.0sp"
    android:layout_gravity="center"
    tools:context=".SetupActivity">

    <ImageView
        android:layout_width="300dp"
        android:layout_gravity="center"
        android:layout_height="130dp"
        android:layout_marginTop="13dp"
        android:background="@drawable/setup_text"
        android:id="@+id/setupText"
        ></ImageView>

        <androidx.appcompat.widget.SearchView
            android:layout_width="match_parent"
            android:layout_height="65dp"
            android:id="@+id/searchViewSetup"
            android:theme="@style/AppTheme.Toolbar"
            app:iconifiedByDefault="false"
            ></androidx.appcompat.widget.SearchView>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:paddingHorizontal="8dp"
        android:layout_height="wrap_content">
        <ListView
            android:id="@+id/list_item"
            android:layout_gravity="center"
            android:layout_width="395dp"
            android:divider="@android:color/transparent"
            android:dividerHeight="10.0sp"
            android:layout_height="wrap_content"
            tools:listitem="@layout/activity_ingredients_layout"
            android:paddingBottom="10.0sp"
            android:clipToPadding="false"
            android:scrollbars="none"
            android:paddingTop="10.0sp">
        </ListView>

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="@drawable/setup_btn_shadow"
            android:layout_marginLeft="287dp"
            android:layout_marginTop="450dp"
            android:alpha="0.5"
            ></ImageView>

        <android.widget.Button
            android:layout_width="73dp"
            android:id="@+id/setup_floating_btn"
            android:layout_height="73dp"
            android:layout_marginLeft="300dp"
            android:layout_marginTop="460dp"
            android:foregroundGravity="bottom"
            android:src="@drawable/ic_baseline_arrow_forward_ios_24"
            android:background="@drawable/setup_btn"
            ></android.widget.Button>
    </RelativeLayout>



</LinearLayout>

java:

package com.example.yummilyproject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;

import com.example.yummilyproject.databinding.ActivitySetupFridgeBinding;

import java.util.ArrayList;

public class SetupActivity extends AppCompatActivity implements View.OnClickListener {

    ActivitySetupFridgeBinding binding;

    SearchView searchView;
    ListView listView;
    Button btn;

    String[] ingredients = {"Avocado", "Tomato", "Pasta", "Cauliflower", "Egg", "Salmon", "Chicken", "Beef", "Broccoli", "Cheese", "Zucchini", "Lemon", "Sweet Potato", "Kale", "Carrot", "Black Beans", "Asparagus",
            "Spinach", "Rice", "Potato", "Yoyo Beans"};
    Boolean[] checkboxes = {false, false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false};
    int[] images = {R.drawable.ic_launcher_foreground, R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,
            R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,
            R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,
            R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_setup_fridge);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        listView = findViewById(R.id.list_item);
        searchView = findViewById(R.id.searchViewSetup);
        btn = (Button) findViewById(R.id.setup_floating_btn);
        btn.bringToFront();
        btn.setOnClickListener(this);


        binding = ActivitySetupFridgeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());



        ArrayList<Ingredient> ingredientArrayList = new ArrayList<>();
        for (int i = 0; i < images.length; i++) {
            Ingredient ingredient = new Ingredient(ingredients[i], images[i], checkboxes[i]);
            ingredientArrayList.add(ingredient);
        }

        ListAdapter listAdapter = new ListAdapter(SetupActivity.this, ingredientArrayList);
        binding.listItem.setTextFilterEnabled(true);
        binding.listItem.setAdapter(listAdapter);
        binding.listItem.setClickable(true);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                listAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                listAdapter.getFilter().filter(newText);
                return false;
            }
        });


        binding.listItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Ingredient ig = (Ingredient) parent.getItemAtPosition(position);
                ig.setIngredientCheckBox(!ig.isIngredientCheckBox());
                CheckBox cb = view.findViewById(R.id.ingredientChekcBox);
                cb.setChecked(!cb.isChecked());
                //cb.setChecked(!cb.isChecked());
            }
        });


    }

    @Override
    public void onClick(View v) {
        v.startAnimation(buttonClick);
        if (v == findViewById(R.id.setup_floating_btn))
        {
            System.out.println("press btn");
            String[] ingredientsList = new String[ingredients.length];
            int cnt = 0;
            for (int i = 0; i<ingredients.length; i++)
            {
                if (checkboxes[i] == true)
                {
                    ingredientsList[cnt] = ingredients[i];
                    cnt++;
                }
            }
            System.out.println(ingredientsList);
            Intent intent = new Intent (this, MainActivity.class);
            intent.putExtra("ingredientsList", ingredientsList);

        }
    }

    private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);


    public class Ingredient
    {
        private String ingredientTitle;
        private int ingredientPhoto;
        private boolean ingredientCheckBox;

        public Ingredient(String ingredientTitle, int ingredientPhoto, boolean ingredientCheckBox) {
            this.ingredientTitle = ingredientTitle;
            this.ingredientPhoto = ingredientPhoto;
            this.ingredientCheckBox = ingredientCheckBox;
        }

        public String getIngredientTitle() {
            return ingredientTitle;
        }

        public void setIngredientTitle(String ingredientTitle) {
            this.ingredientTitle = ingredientTitle;
        }

        public int getIngredientPhoto() {
            return ingredientPhoto;
        }

        public void setIngredientPhoto(int ingredientPhoto) {
            this.ingredientPhoto = ingredientPhoto;
        }

        public boolean isIngredientCheckBox() {
            return ingredientCheckBox;
        }

        public void setIngredientCheckBox(boolean ingredientCheckBox) {
            this.ingredientCheckBox = ingredientCheckBox;
        }
    }

    public class ListAdapter extends ArrayAdapter<Ingredient>
    {
        public ListAdapter (Context context, ArrayList<Ingredient> ingredientList)
        {
            super(context, R.layout.activity_ingredients_layout, ingredientList);
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            Ingredient ingredient = getItem(position);
            if (convertView == null)
            {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_ingredients_layout, parent, false);
            }

            ImageView imageView = convertView.findViewById(R.id.ingredientPhoto);
            TextView title = convertView.findViewById(R.id.ingredientTitle);
            CheckBox cb  = convertView.findViewById(R.id.ingredientChekcBox);
            imageView.setImageResource(ingredient.ingredientPhoto);
            title.setText(ingredient.ingredientTitle);
            cb.setActivated(ingredient.ingredientCheckBox);


            return convertView;
        }
    }

    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }


}

【问题讨论】:

    标签: android android-studio android-layout android-button android-studio-3.0


    【解决方案1】:

    你使用相等的方式是错误的。您不能使用== 来查看两个对象是否相等。

    如果你真的想使用equals 来验证它是同一个对象,你应该这样做:

    if (v.equals(findViewById(R.id.setup_floating_btn)) {
        // Do whatever you need to do when the button is clicked here.
    }
    

    虽然这可行,但不推荐使用此方法来验证这是否是点击的 View。相反,您应该像这样检查点击的ViewID

    if (v.getId() == R.id.setup_floating_btn) {
        // Do whatever you need to do when the button is clicked.
    }
    

    看看equals==here之间的区别。

    附带说明:您将这里的内容混合在一起 - ViewBindings 与普通的findViewById 非常糟糕,并且使事情变得非常难以阅读。 ViewBindings 的目的是让屏幕中的所有视图更容易膨胀,并使所有对视图的引用类型安全并确保没有视图为空。您可能也应该阅读此内容。

    同样在您的 XML 中,您使用 sp 作为 dividerHeightpadding 的单位,这是完全错误的。 sp 单位仅用于文本,而不用于视图的高度或填充。

    还可以看看bringToFront()View 上的作用,看看这是否真的应该在你的Button 上应用/使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多