Нужна помощь в классе Java OnClickListener () и переключателе (v.getId)

#java #android #class

#java #Android #класс

Вопрос:

Я создаю простую панель мониторинга CardView, следуя руководству Youtube. Все шло гладко, пока я не попытался установить OnClickListener для представления.

Когда я попытался получить доступ к переменной в определении CardView в методе onCreate, он обращается к идентификатору на моем activity_main.xml вместо этого.

Редактор продолжает показывать красную метку, когда я пытался получить доступ к переменной определения.

Я обычно использую android: onClick вместо прослушивателя одним щелчком мыши, поскольку я новичок в этих вещах программирования, я хотел бы попробовать что-то новое.

это мой класс java activity_main

 package com.budiluhur.mylibrary;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.view.View.OnClickListener;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public CardView katalog;
    public CardView updateKatalog;
    public CardView help;
    public CardView exit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        katalog = (CardView) findViewById(R.id.Katalog);
        updateKatalog = (CardView) findViewById(R.id.UpdateKatalog);
        help = (CardView) findViewById(R.id.Help);
        exit = (CardView) findViewById(R.id.Exit);

        //Listener
        katalog.setOnClickListener(this);
        updateKatalog.setOnClickListener(this);
        help.setOnClickListener(this);
        exit.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {


        Intent i;
        switch (v.getId()) {

            case R.id.updateKatalog:
                i = new Intent(this, KatalogBuku.class);
                break;


            default:
                break;
        }


    }

}

  

и это мой activity_main.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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:padding="10dp"
    android:background="#fcfcfc"
    android:gravity="center"
    android:id="@ id/ll">

    <LinearLayout
        android:clipToPadding="false"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.CardView
            android:foreground="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:id="@ id/Katalog"
            android:layout_width="160dp"
            android:layout_height="190dp"
            android:layout_margin="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">
                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:background="@drawable/circlebackgroundpurple"
                    android:src="@drawable/ic_katalog"
                    android:padding="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"
                    android:text="Katalog"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/lightGrey"
                    android:layout_margin="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Check Katalog Buku"
                    android:padding="5dp"
                    android:textColor="@android:color/darker_gray"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            android:id="@ id/UpdateKatalog"
            android:foreground="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:layout_width="160dp"
            android:layout_height="190dp"
            android:layout_margin="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">

                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:background="@drawable/circlebackgroundyellow"
                    android:padding="10dp"
                    android:src="@drawable/ic_update_library" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"
                    android:text="Update Katalog"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/lightGrey"
                    android:layout_margin="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Update Katalog Buku"
                    android:padding="5dp"
                    android:textColor="@android:color/darker_gray"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>

    </LinearLayout>
    <LinearLayout
        android:clipToPadding="false"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.CardView
            android:id="@ id/Help"
            android:foreground="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:layout_width="160dp"
            android:layout_height="190dp"
            android:layout_margin="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">
                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:background="@drawable/circlebackgroundgreen"
                    android:src="@drawable/ic_help_black_24dp"
                    android:padding="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"

                    android:text="Help"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/lightGrey"
                    android:layout_margin="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Bantuan Aplikasi"
                    android:padding="5dp"
                    android:textColor="@android:color/darker_gray"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            android:id="@ id/Exit"
            android:foreground="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:layout_width="160dp"
            android:layout_height="190dp"
            android:layout_margin="10dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:orientation="vertical">

                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:background="@drawable/circlebackgroundaccent"
                    android:padding="10dp"
                    android:src="@drawable/ic_exit_to_app_black_24dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:text="Exit"
                    android:textStyle="bold" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:layout_margin="10dp"
                    android:background="@color/lightGrey" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:padding="5dp"
                    android:text="Keluar Aplikasi"
                    android:textColor="@android:color/darker_gray" />

            </LinearLayout>
        </android.support.v7.widget.CardView>

    </LinearLayout>
    <LinearLayout
        android:clipToPadding="false"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


    </LinearLayout>
</LinearLayout>
  

то, к чему я пытаюсь получить доступ, — это «updateKatalog» в классе onCreate, а не UpdateKatalog, который находится в файле XML.

ищу ваш полезный ответ.

Комментарии:

1. В чем именно проблема? В switch ? Если это так, case R.id.updateKatalog: должно быть case R.id.UpdateKatalog: прописным U , поскольку именно так вы определили его в макете XML.

2. привет, Майк, большое спасибо за ваш ответ. это работает! я думал, что R.id имеет в виду «updateKatalog». я только что понял, что это относится к идентификатору в xml. большое спасибо, Майк! @MikeM.

Ответ №1:

В вашем XML-файле макета вы определяете идентификатор как «@ id / UpdateKatalog»

В вашем методе findViewById, также вызывая его R.id.UpdateKatalog

Но в вашем случае вы используете регистр R.id.updateKatalog:

Вам нужно ввести U в верхний регистр в каталоге обновлений

Комментарии:

1. Привет, Майкл, да, ты на 100% прав. я думал, что это относится к переменной ‘updateKatalog’, потому что я определил ‘UpdateKatalog’ как updateKatalog в классе ‘onCreate’. спасибо, что помогли мне!