Как сделать textView видимым после события onClick и изменения Activity? - PullRequest
0 голосов
/ 19 сентября 2019

В моем просмотре прокрутки есть три отрывка, каждый из которых должен стать видимым после события onclick на одной из трех кнопок.

В настоящее время я установил их все невидимыми.И поскольку я не могу заставить его работать, я пробую его только с одним из отрывков.

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

Я включил свой MainActivity.java и XML-файл, который я использовал для установки невидимого.

package com.example.threebuttons;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView passage1;

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

        passage1 = findViewById(R.id.passage_1);
    }

    public void launchPassageOne(View view) {
        passage1.setVisibility(view.VISIBLE);
        Intent intent = new Intent(this, PassageActivity.class);
        startActivity(intent) ;
    }

    public void launchPassageTwo(View view) {
        Intent intent = new Intent(this, PassageActivity.class);
        startActivity(intent) ;
    }

    public void launchPassageThree(View view) {
        Intent intent = new Intent(this, PassageActivity.class);
        startActivity(intent) ;
    }
}

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".PassageActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

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

            <EditText
                android:id="@+id/passage_1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:gravity="start|top"
                android:inputType="textMultiLine"
                android:text="@string/passage1"
                android:visibility="invisible"/>

            <EditText
                android:id="@+id/passage_2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:gravity="start|top"
                android:inputType="textMultiLine"
                android:text="@string/passage2"
                android:visibility="invisible"/>

            <EditText
                android:id="@+id/passage_3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:gravity="start|top"
                android:inputType="textMultiLine"
                android:text="@string/passage3"
                android:visibility="invisible"/>

        </LinearLayout>
    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

Моя программа просто падает.И я не могу найти никаких сообщений об ошибках.

Как сделать пакеты видимыми, когда я хочу, чтобы активность изменилась?Есть три отрывка, которые я хочу, чтобы каждый стал видимым для соответствующей кнопки, а затем стал невидимым, если нажата кнопка «Назад».

Ответы [ 4 ]

2 голосов
/ 20 сентября 2019

Это швы, три вида находятся в начатом действии.И поэтому вы не можете изменить их видимость, потому что они не были созданы.

Добавьте это перед началом действия intent.putExtra("passageNum", 1) Затем вызовите startActivity(intent)

В PassageAactivity onCreate выполните следующее:

If (getIntent().hasExtra("passageNum") && getIntent().getExtras().getInt("passageNum") == 1)
    passage1.setVisibility(View.VISIBLE)

И так далее для других представлений

0 голосов
/ 20 сентября 2019

Изображение нажмите здесь Что бы я не понял из вашего кода, я понял, что вы не инициализируете свои методы в On create, все, что определено вне On create, не будет использоваться до тех пор, пока не будет вызвано изнутри метода On create,Разработанный код может помочь вам лучше понять.В приведенном ниже коде я сделал прокручиваемые текстовые представления, но вы можете прокручивать их только в том случае, если текст слишком длинный для заполнения всего текстового представления.MainActivity.java

package com.example.threebuttons;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    EditText edit1;
    EditText edit2;
    EditText edit3;

    Button btn1;
    Button btn2;
    Button btn3;
    Button btnV;
    Button btnI;

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


            // defining id for edit texts
            edit1=findViewById(R.id.passage_1);
            edit2=findViewById(R.id.passage_2);
            edit3=findViewById(R.id.passage_3);

            // defining id for buttons
            btn1=findViewById(R.id.button_1);
            btn2=findViewById(R.id.button_2);
            btn3=findViewById(R.id.button_3);
            btnV=findViewById(R.id.btnvisi);
            btnI=findViewById(R.id.btninvisi);

            // defining id for text views
            t1=findViewById(R.id.textview1);
            t2=findViewById(R.id.textview2);
            t3=findViewById(R.id.textview3);

            // making text views scrollable

            t1.setMovementMethod(new ScrollingMovementMethod());
            t2.setMovementMethod(new ScrollingMovementMethod());
            t3.setMovementMethod(new ScrollingMovementMethod());

            btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    t1.setText(edit1.getText().toString());

                }
            });
            btn2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    t2.setText(edit2.getText().toString());
                }
            });

            btn3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    t3.setText(edit3.getText().toString());

                }
            });

            btnV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //Making passages Visible
                    t1.setVisibility(View.VISIBLE);
                    t2.setVisibility(View.VISIBLE);
                    t3.setVisibility(View.VISIBLE);
                }
            });

            btnI.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    t1.setVisibility(View.INVISIBLE);
                    t2.setVisibility(View.INVISIBLE);
                    t3.setVisibility(View.INVISIBLE);

                }
            });

    }
}

Установите Activitymain.xml, как показано ниже

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    android:background="#2196F3"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/passage_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:ems="10"
        android:hint="passage 1"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.043"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.016" />

    <EditText
        android:id="@+id/passage_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:ems="10"
        android:hint="Passage 2"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.043"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.102" />

    <EditText
        android:id="@+id/passage_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:ems="10"
        android:hint="Passage 3"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.043"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.194" />

    <Button
        android:id="@+id/button_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="Button"
        app:layout_constraintBottom_toTopOf="@+id/passage_2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/passage_1"
        app:layout_constraintTop_toTopOf="@+id/passage_1" />

    <Button
        android:id="@+id/button_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="Button"
        app:layout_constraintBottom_toTopOf="@+id/passage_3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/passage_2"
        app:layout_constraintTop_toTopOf="@+id/passage_2" />

    <Button
        android:id="@+id/button_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="@+id/passage_3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/passage_3"
        app:layout_constraintTop_toTopOf="@+id/passage_3" />

    <TextView
        android:id="@+id/textview1"
        android:layout_width="319dp"
        android:layout_height="74dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:background="#3F51B5"
        android:hint="Passage 1"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.486"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.446"
        tools:visibility="invisible" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="319dp"
        android:layout_height="74dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:background="#3F51B5"
        android:hint="Passage 2"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.672"
        tools:visibility="invisible" />

    <TextView
        android:id="@+id/textview3"
        android:layout_width="319dp"
        android:layout_height="74dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:background="#3F51B5"
        android:hint="Passage 3"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.486"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.895"
        tools:visibility="invisible" />

    <Button
        android:id="@+id/btnvisi"
        android:layout_width="175dp"
        android:layout_height="44dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="Passage Visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.036"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.299" />

    <Button
        android:id="@+id/btninvisi"
        android:layout_width="174dp"
        android:layout_height="47dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="passage invisible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.886"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.3" />
</androidx.constraintlayout.widget.ConstraintLayout>

Надеюсь, это поможет вам лучше понять, Спасибо

0 голосов
/ 19 сентября 2019

Используйте View.VISIBLE, заглавную V, это целочисленная константа из класса View.Удалите аргумент View из метода launchPassageOne:

public void launchPassageOne() {
    passage1.setVisibility(View.VISIBLE);
    Intent intent = new Intent(this, PassageActivity.class);
    startActivity(intent) ;
}
0 голосов
/ 19 сентября 2019
passage1.setVisibility(View.VISIBLE)

Подробнее о представлениях и о том, как изменить их поведение, можно узнать здесь: https://developer.android.com/reference/android/view/View

...