Cardview не изменит мою текущую деятельность (Intent не будет работать) - PullRequest
0 голосов
/ 08 января 2019

Я создаю языковое приложение как домашнее задание для школы в Android.
Прямо сейчас я настраиваю некоторые интерактивные CardViews (которые находятся в «LevelsHub»), чтобы перевести пользователя в другое представление (называемое «ProfileActivity»), но по какой-то причине INTENT работает не так, как должно, он возвращает меня к тому же представлению («LevelsHub»), хотя я использовал его в некоторых других частях приложения. Что здесь может происходить?

Я следовал этому удивительному учебнику по чувству.
https://www.youtube.com/watch?v=VUPM387qyrw и этот тоже https://www.youtube.com/watch?v=K2V6Y7zQ8NU

Пробовал нажимать на карточки сам, не получалось Я уже пытался добавить кнопки на карту и использовать Intent на ней тоже не сработало. Цикл по всем картам, чтобы посмотреть, заберет ли я их где-нибудь Используя метод этого парня switch https://www.youtube.com/watch?v=d6CfaWW7G5Q Я пытался разделить их один за другим, тот же результат
package com.example.salo7.totonaku;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.Toast;

public class LevelsHub extends AppCompatActivity implements 
View.OnClickListener {

 //GridLayout mainGrid;
 //CardView pronombresCard1;
 //CardView numeros1Card2;
 //CardView numeros2Card3;
 private Button  pronombresBtn1;

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

     //mainGrid = (GridLayout) findViewById(R.id.mainGrid);
     pronombresBtn1 = (Button) findViewById(R.id.pronombresBtn1);
     //numeros1Btn2 = (Button) findViewById(R.id.numeros1Btn2);
     //numeros2Btn3 = (Button) findViewById(R.id.numeros2Btn3);

     //Add click listener
     pronombresBtn1.setOnClickListener(this);


     //Set Event
     //setSingleEvent (mainGrid);
     //setToggleEvent (mainGrid);
 }

@Override
public void onClick(View v) {
    Intent i;

    switch (v.getId()){
        case R.id.pronombresBtn1 : i = new Intent(LevelsHub.this, 
profileActivity.class);startActivity(i); break;
        default:break;
    }
}

/*private void setToggleEvent(GridLayout mainGrid) {
    //ciclar childs de mainGrid
    for (int i=0;i<mainGrid.getChildCount();i++){
        final CardView cardView = (CardView) mainGrid.getChildAt(i);
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cardView.getCardBackgroundColor().getDefaultColor() == 
-1){
                    //Cambia el color

cardView.setCardBackgroundColor(Color.parseColor("#FF6F00"));
                    Toast.makeText(LevelsHub.this,"State: 
true",Toast.LENGTH_SHORT).show();
                }else{

cardView.setCardBackgroundColor(Color.parseColor("#FFFFFF"));
                    Toast.makeText(LevelsHub.this,"State: 
false",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}*/

/*private void setSingleEvent(GridLayout mainGrid) {
    //ciclar childs de mainGrid
    for (int i=0;i<mainGrid.getChildCount();i++){
        CardView cardView = (CardView) mainGrid.getChildAt(i);
        final int finalI = i;
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(LevelsHub.this,"Cliqueado en index " + 
finalI,Toast.LENGTH_SHORT).show();
                if (finalI == 0){
                    Toast.makeText(LevelsHub.this,"Clicado 
pronombres",Toast.LENGTH_SHORT).show();
                    Intent accountIntent = new Intent(LevelsHub.this, 
profileActivity.class);
                    startActivity(accountIntent);
                    finish();
                }
            }
        });
    }
 }*/
}

Это должно привести меня только к другому взгляду, кто-нибудь может мне немного помочь?

UPDATE Не знал, что 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:orientation="vertical"
android:weightSum="10"
tools:context=".LevelsHub">
<!--android:background="@drawable/bg"-->
<RelativeLayout
    android:layout_weight="2"
    android:layout_width="match_parent"
    android:layout_height="0dp">

    <TextView
        android:id="@+id/textGrid"
        android:text="NIVELES"
        android:textSize="34sp"
        android:textColor="@android:color/white"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

<GridLayout
    android:id="@+id/mainGrid"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="8"
    android:alignmentMode="alignMargins"
    android:columnCount="2"
    android:columnOrderPreserved="false"
    android:padding="14dp"
    android:rowCount="3">

    <!--Row 1-->
    <!--Column 1-->

    <!--Column 2-->
    <android.support.v7.widget.CardView
        android:id="@+id/pronombresCard1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        app:cardCornerRadius="8dp"
        app:cardElevation="8dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_margin="16dp"
            android:orientation="vertical">

            <ImageView
                android:layout_width="107dp"
                android:layout_height="102dp"
                android:layout_gravity="center_vertical"
                android:src="@drawable/logomakr_negro" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Pronombres"
                android:textAlignment="center"
                android:textColor="@android:color/black"
                android:textSize="18sp"
                android:textStyle="bold" />

            <Button
                android:id="@+id/pronombresBtn1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Empezar" />


        </LinearLayout>

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

    <android.support.v7.widget.CardView
        android:id="@+id/numeros1Card2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        app:cardCornerRadius="8dp"
        app:cardElevation="8dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_margin="16dp"
            android:orientation="vertical">

            <ImageView
                android:layout_width="107dp"
                android:layout_height="102dp"
                android:layout_gravity="center_vertical"
                android:src="@drawable/logomakr_negro" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Números 1"
                android:textAlignment="center"
                android:textColor="@android:color/black"
                android:textSize="18sp"
                android:textStyle="bold" />

            <Button
                android:id="@+id/numeros1Btn2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Empezar" />


        </LinearLayout>

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

    <!--Row 2-->
    <!--Column 1-->
    <android.support.v7.widget.CardView
        android:id="@+id/numeros2Card3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        app:cardCornerRadius="8dp"
        app:cardElevation="8dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_margin="16dp"
            android:orientation="vertical">

            <ImageView
                android:layout_width="107dp"
                android:layout_height="102dp"
                android:layout_gravity="center_vertical"
                android:src="@drawable/logomakr_negro" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Números 2"
                android:textAlignment="center"
                android:textColor="@android:color/black"
                android:textSize="18sp"
                android:textStyle="bold" />

            <Button
                android:id="@+id/numeros2Btn3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Empezar" />


        </LinearLayout>

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

    <!--Column 2-->
    <android.support.v7.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        app:cardCornerRadius="8dp"
        app:cardElevation="8dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_margin="16dp"
            android:orientation="vertical">

            <ImageView
                android:layout_width="107dp"
                android:layout_height="102dp"
                android:layout_gravity="center_vertical"
                android:src="@drawable/logomakr_negro" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="¡Más niveles en camino!"
                android:textAlignment="center"
                android:textColor="@android:color/black"
                android:textSize="18sp"
                android:textStyle="bold" />


        </LinearLayout>

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

</GridLayout>

</LinearLayout>

Ответы [ 3 ]

0 голосов
/ 08 января 2019

Добавьте два свойства в вашем CardView

android:clickable="true"
android:focusable="true"

Это будет работать.

Не стесняйтесь комментировать, если у вас возникли проблемы.

0 голосов
/ 10 января 2019

Так что, в основном, после некоторых копаний, отладки и прочего я смог найти ответ на свою проблему. В основном это было то, что LevelsHub активность была правильной, но в моей profileActivity активности у меня была кнопка, которая неправильно связывалась с OnClickListener, которую я имел для нее, поэтому все, что я делал, было правильно, и теперь работает как шарм ,
Спасибо всем, кто помог мне и дал несколько советов.

0 голосов
/ 08 января 2019

У вас есть код для начала действия в той же строке, поэтому код после ; будет пропущен. Правильно отформатируйте код и переместите startActivity() на следующую строку.

case R.id.pronombresBtn1 : 
    i = new Intent(LevelsHub.this,profileActivity.class);
    startActivity(i); 
break;
...