Нажатие кнопки отладки Android Studio - событие не срабатывает - PullRequest
0 голосов
/ 24 апреля 2019

Я создал этот экран, используя дизайн экрана режима дизайна.

enter image description here

XML для этого

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".ftpDetails">

    <Button
        android:id="@+id/btnTest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="11dp"
        android:layout_marginLeft="11dp"
        android:layout_marginBottom="16dp"
        android:text="@string/test"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/txtPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="96dp"
        android:layout_marginLeft="96dp"
        android:layout_marginTop="292dp"
        android:width="250dp"
        android:ems="10"
        android:importantForAutofill="no"
        android:inputType="textPassword"
        android:textSize="12sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:targetApi="o" />

    <EditText
        android:id="@+id/txtUsername"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="100dp"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="216dp"
        android:width="250dp"
        android:ems="10"
        android:importantForAutofill="no"
        android:inputType="text"
        android:textSize="12sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:targetApi="o" />

    <EditText
        android:id="@+id/txtFolder"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="96dp"
        android:layout_marginLeft="96dp"
        android:layout_marginTop="140dp"
        android:width="250dp"
        android:ems="10"
        android:importantForAutofill="no"
        android:inputType="text"
        android:textSize="12sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:targetApi="o" />

    <EditText
        android:id="@+id/txtServer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="96dp"
        android:layout_marginLeft="96dp"
        android:layout_marginTop="68dp"
        android:width="250dp"
        android:ems="10"
        android:importantForAutofill="no"
        android:inputType="text"
        android:textSize="12sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:targetApi="o" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="225dp"
        android:text="@string/username"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="300dp"
        android:text="@string/password"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2"
        app:layout_constraintStart_toStartOf="@+id/textView4"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="17dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="150dp"
        android:text="@string/ftp_folder"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="75dp"
        android:text="@string/ftp_server"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/login_credentials"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        android:text="@string/save"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>

Этот вопрос основан на нижней части XML с кнопкой btnSave.

В моем классе Java для этого занятия я попытался создать onClickListener, например,

import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ftpDetails extends AppCompatActivity{
private TextView txtServer;
private TextView txtFolder;
private TextView txtUsername;
private TextView txtPassword;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_ftp_details);
    setTitle(R.string.ftpTitle);

    txtServer = (TextView) findViewById(R.id.txtServer);
    txtFolder = (TextView) findViewById(R.id.txtFolder);
    txtUsername = (TextView) findViewById(R.id.txtUsername);
    txtPassword = (TextView) findViewById(R.id.txtPassword);

findViewById(R.id.btnSave).setOnClickListener(null);

    // Check that all text boxes have a value in them
    if (txtServer.getText().length() == 0)
    {
        // MESSAGE BOX
        AlertDialog.Builder msg = new AlertDialog.Builder(this);
        msg.setTitle("Enter Server");
        msg.setMessage("Please enter a server address.");
        msg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Leave this blank, this will mean nothing happens, the msg just disappears
            }
        });
    }

    if (txtFolder.getText().length() == 0)
    {
        // MESSAGE BOX
        AlertDialog.Builder msg = new AlertDialog.Builder(this);
        msg.setTitle("Enter Folder");
        msg.setMessage("Please enter a folder to use.");
        msg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Leave this blank, this will mean nothing happens, the msg just disappears
            }
        });
    }

    if (txtUsername.getText().length() == 0)
    {
        // MESSAGE BOX
        AlertDialog.Builder msg = new AlertDialog.Builder(this);
        msg.setTitle("Enter Username");
        msg.setMessage("Please enter your username.");
        msg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Leave this blank, this will mean nothing happens, the msg just disappears
            }
        });
    }

    if (txtPassword.getText().length() == 0)
    {
        // MESSAGE BOX
        AlertDialog.Builder msg = new AlertDialog.Builder(this);
        msg.setTitle("Enter Server");
        msg.setMessage("Please enter a your password.");
        msg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Leave this blank, this will mean nothing happens, the msg just disappears
            }
        });
    }
  }
}

У меня есть точки останова на линиях

super.onCreate(savedInstanceState);

findViewById(R.id.btnSave).setOnClickListener(null);

и

if (txtServer.getText().length() == 0)

Однако, когда я отлаживаю приложение (Shift + F9) на подключенном устройстве (OnePlus 6T), ни одна източки останова поражены.Кроме того, когда я нажимаю кнопку и текстовые поля остаются пустыми, оповещения о сообщениях не отображаются.

Я что-то не так сделал?Я попытался использовать атрибут XML onClick:, но у него был тот же результат, а также установить тот же атрибут в режиме разработки, но опять не было никаких изменений.

РЕДАКТИРОВАТЬ

Следуя подсказкам в ответах, у меня в настоящее время есть это

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_ftp_details);
    setTitle(R.string.ftpTitle);

    txtServer = (TextView) findViewById(R.id.txtServer);
    txtFolder = (TextView) findViewById(R.id.txtFolder);
    txtUsername = (TextView) findViewById(R.id.txtUsername);
    txtPassword = (TextView) findViewById(R.id.txtPassword);

    findViewById(R.id.btnSave).setOnClickListener(btnSaveListener);
}

private View.OnClickListener btnSaveListener =new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // my code in here
        }
    }

Но все равно я не получаю результата.

РЕДАКТИРОВАТЬ 2

После дальнейшего изучения, когда я нажимаю кнопку, в окне logcat отображается следующая информация

2019-04-24 14: 25: 57.866 28031-28031 / com.example.my_test_app W / RenderThread:аудит = 1400 (0.0: 425186): avc: отказано {чтение} для имени = "u: object_r: vendor_default_prop: s0" dev = "tmpfs" ino = 22761 scontext = u: r: untrusted_app: s0: c129, c256,c512, c768 tcontext = u: object_r: vendor_default_prop: s0 tclass = file permissive = 0

2019-04-24 14: 25: 57.875 28031-28057 / com.example.my_test_app E / libc: доступ запрещенсвойство "vendor.debug.egl.swapinterval"

2019-04-24 14: 25: 57.886 28031-28057 / com.example.my_test_app E /libc: доступ запрещен при поиске свойства "vendor.debug.egl.swapinterval"

2019-04-24 14: 25: 57.876 28031-28031 / com.example.my_test_app W / RenderThread: type = 1400 аудит (0,0: 425187): avc: запрещено {read} для name = "u: object_r: vendor_default_prop: s0" dev = "tmpfs" ino = 22761 scontext = u: r: untrusted_app: s0: c129, c256, c512, c768 tcontext = u: object_r: vendor_default_prop: s0 tclass = файл разрешен = 0

2019-04-24 14: 25: 57.896 28031-28031 / com.example.my_test_app W / RenderThread: type = 1400 аудит (0,0: 425188): avc: запрещено {read} для name = "u: object_r: vendor_default_prop: s0" dev = "tmpfs" ino = 22761 scontext = u: r: untrusted_app: s0: c129, c256, c512, c768 tcontext = u: object_r:vendor_default_prop: s0 tclass = файл разрешен = 0

2019-04-24 14: 25: 57.903 28031-28057 / com.example.my_test_app E / libc: доступ к файлу поиска запрещен "vendor.debug.egl.swapinterval"

2019-04-24 14: 25: 57,916 28031-28031 / com.example.my_test_app W / RenderThread: type = 1400 аудит (0,0: 425189): avc: отказано {читать} дляname = "u: object_r: vendor_default_prop: s0" dev = "tmpfs" ino = 22761 scontext = u: r: untrusted_app: s0: c129, c256, c512, c768 tcontext = u: object_r: vendor_default_prop: s0 tclass = файл0

2019-04-24 14: 25: 57.923 28031-28057 / com.example.my_test_app E / libc: доступ запрещен при поиске свойства "vendor.debug.egl.swapinterval"

2019-04-24 14: 25: 57.942 28031-28057 / com.example.my_test_app E / libc: доступ запрещен при поиске свойства "vendor.debug.egl.swapinterval"

2019-04-24 14:25:57.926 28031-28031 / com.example.my_test_app W / RenderThread: type = 1400 аудит (0.0: 425190): avc: отклонено {read} для имени = "u: object_r: vendor_default_prop: s0" dev = "tmpfs" ino = 22761scontext = u: r: untrusted_app: s0: c129, c256, c512, c768 tcontext = u: object_r: vendor_default_prop: s0 tclass = файл разрешен = 0

2019-04-24 14: 25: 57,954 28031-28057 / com.example.my_test_app E / libc: доступ запрещен при поиске свойства "vendor.debug.egl.swapinterval"

--------- начало системы

2019-04-24 14: 25: 58.237 28031-28057 / com.example.my_test_app I / chatty: uid = 10129 (com.example.my_test_app) RenderThread, идентичный 17 строкам

2019-04-24 14: 25: 58.252 28031-28057 / com.example.my_test_app E / libc: доступ запрещен при поиске свойства "vendor.debug.egl.swapinterval"

Ответы [ 6 ]

0 голосов
/ 01 мая 2019

В конце концов, это не было проблемой с тем, как я настраивал своего слушателя.

Изменение вызова активности с моего MainActivity класса запуска на StartActivity означало, что код OnCreate был вызван правильно.

0 голосов
/ 24 апреля 2019

Ваша реализация прослушивателя при нажатии кнопки неверна, попробуйте так:

 findViewById(R.id.action_ask).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Check that all text boxes have a value in them
                if (txtServer.getText().length() == 0)
                {
                    // MESSAGE BOX
                    AlertDialog.Builder msg = new AlertDialog.Builder(this);
                    msg.setTitle("Enter Server");
                    msg.setMessage("Please enter a server address.");
                    msg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Leave this blank, this will mean nothing happens, the msg just disappears
                        }
                    });
                }

                if (txtFolder.getText().length() == 0)
                {
                    // MESSAGE BOX
                    AlertDialog.Builder msg = new AlertDialog.Builder(this);
                    msg.setTitle("Enter Folder");
                    msg.setMessage("Please enter a folder to use.");
                    msg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Leave this blank, this will mean nothing happens, the msg just disappears
                        }
                    });
                }

                if (txtUsername.getText().length() == 0)
                {
                    // MESSAGE BOX
                    AlertDialog.Builder msg = new AlertDialog.Builder(this);
                    msg.setTitle("Enter Username");
                    msg.setMessage("Please enter your username.");
                    msg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Leave this blank, this will mean nothing happens, the msg just disappears
                        }
                    });
                }

                if (txtPassword.getText().length() == 0)
                {
                    // MESSAGE BOX
                    AlertDialog.Builder msg = new AlertDialog.Builder(this);
                    msg.setTitle("Enter Server");
                    msg.setMessage("Please enter a your password.");
                    msg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Leave this blank, this will mean nothing happens, the msg just disappears
                        }
                    });
                }
            }
        });
0 голосов
/ 24 апреля 2019

почему вы используете прослушиватель кликов следующим образом: findViewById(R.id.btnSave).setOnClickListener(null);

сделайте это вместо:

findViewById(R.id.btnSave).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //put all your textView logic here
            }
        });
0 голосов
/ 24 апреля 2019

Измените эту строку:

findViewById(R.id.btnSave).setOnClickListener(null);

на

findViewById(R.id.btnSave).setOnClickListener(btnSaveListener);

и удалите следующие строки из метода onCreate.

Затем создайте btnSaveListener следующим образом:

private View.OnClickListener btnSaveListener =new View.OnClickListener() {

   @Override
   public void onClick(View v) {
      // here goes all the code belove the line you change in the method `onCreate`
   }
};
0 голосов
/ 24 апреля 2019

Вы неправильно настраиваете слушателя. Добавьте следующий код:

Button btnSave = (Button) findViewById(R.id.btnSave);

btnSave.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //add your conditions here
    }
0 голосов
/ 24 апреля 2019

.setOnClickListener(null) не назначит никаких OnClickListener; так как вы собираетесь отлаживать это событие? и что .getText().length(), вероятно, должно быть .getText().toString().length() ... чтобы условие могло быть выполнено.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...