如何使用Android Studio中的接口在两个对象上执行onClickListener?

f45qwnt8  于 2022-12-21  发布在  Android
关注(0)|答案(2)|浏览(87)

我有一个扩展View.onClickListener的Fragment类,我实现了 @overriden 方法,即onClick
我有2个imageView,它执行onClickListener

  1. filterIcon.setOnClickListener(this)
  2. fab.setOnClickListener(this)
    并在 @overriden 方法中设置两个活动,即**onClick()**。
    我想知道onClickListener是否有可能调用相关的clickEvent?如果有,如何调用?如果没有,为什么?
    下面是我的代码:
public class ExpenseFragment extends Fragment implements View.OnClickListener {
    private TextView totalExpenseTV;
    private FloatingActionButton fab;
    private RecyclerView recyclerView;
    private ImageView filterIcon;
    private PieChart pieChart;

    private Animation rotateForward, rotateBackward;

    private FirebaseRecyclerOptions<ExpenseModel> options;
    private MyAdapter adapter;

    private int calendarImgClick = 0;
    private int groceryClick = 0;
    private int bikeClick = 0;
    private int rentClick = 0;
    private int foodsClick = 0;
    private int beerClick = 0;
    private int setCalClick = 0;

    private String whichCategorySelected = "";
    private String selectedDate;

    public void onViewCreated(@NonNull View attachInParentView, Bundle savedInstanceState) {
        super.onViewCreated(attachInParentView, savedInstanceState);
        findViewByIDS(attachInParentView);
        setupRecyclerView();
        fabAnimation();
        fab.setOnClickListener(this);
        filterIcon.setOnClickListener(this);
        databaseListener();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_expense, container, false);
    }

    @Override
    public void onClick(View view) {
        fab.startAnimation(rotateForward);
        rotateForward.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                addNote();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        filterIcon.setBackgroundResource(R.drawable.filter_off);
    }
0aydgbwb

0aydgbwb1#

@Override
public void onClick(View view) {
    if (view.getId() == R.id.filterIcon) {
        // codul care se executează când este apăsată imaginea filterIcon
    } else if (view.getId() == R.id.fab) {
        // codul care se executează când este apăsată imaginea fab
    }
}
uttx8gqw

uttx8gqw2#

您可以使用Kotlin尝试以下操作:

@Override
public void onClick(View view) {
    when (view.getId) {
        R.id.filterIcon -> {
            //do something
        }

        R.id.fab -> {
            //do something
        }
    }
}

相关问题