Как открыть макет при нажатии кнопки (android)

Как я могу открыть другой XML файл макета, когда я нажимаю кнопку в файле main.xml?

так что если у меня есть main.xml, который имеет нажатие кнопки, нажмите здесь, и я нажму на него, откроется файл second.xml(макет).

Ответы

Ответ 1

Этот учебник объясняет, что вам нужно шаг за шагом.

Сначала Создайте два макета:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"  >

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#000000"
    android:text="This is Activity 1" />

       <Button android:text="Next"
        android:id="@+id/Button01"
        android:layout_width="250px"
            android:textSize="18px"
        android:layout_height="55px">
    </Button>    

</LinearLayout>

second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"  >

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#000000"
    android:text="This is Activity 2" />

       <Button android:text="Previous"
        android:id="@+id/Button02"
        android:layout_width="250px"
            android:textSize="18px"
        android:layout_height="55px">
    </Button>    

</LinearLayout>

Второе Добавьте свою активность в файл манифеста

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.rr"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Activity1"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Activity2"></activity>
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest>

Activity1.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Activity1 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button next = (Button) findViewById(R.id.Button01);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), Activity2.class);
                startActivityForResult(myIntent, 0);
            }

        });
    }
}

Чтобы переключиться на Activity2, вам необходимо:

  • Получает ссылку на кнопку с ID Button01 на макете, используя (Button) findViewById(R.id.Button01).

  • Создайте прослушиватель OnClick для кнопки.

  • И самая важная часть, создает "намерение", чтобы начать другой   Мероприятия. Замысел требует двух параметров: контекста и имени   активность, которую мы хотим запустить (Activity2.class)

Activity2.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Activity2 extends Activity {

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        Button next = (Button) findViewById(R.id.Button02);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            }

        });
    }

Ответ 2

-Нажмите кнопку из xml
-add onClickListener на нем
-set новый макет в событии onClick

Button btn = (Button) findViewById(R.id.myButton);
btn.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v)
{
    MyActivity.setContentView(R.layout.newlayout);
}

});

Что-то вроде этого должно работать...

Ответ 3

Котлинский путь:

-Add событие onClick непосредственно в конструкторе.

  1. Откройте файл активности (например, Activity1.xml) в режиме конструктора.
  2. Выберите кнопку, которая вызовет переход
  3. Добавьте имя функции в поле onClick правой панели со всеми свойствами кнопок.

-Open Активность .kt файл

  1. Добавьте функцию с именем, которое вы только что определили в конструкторе

    fun openActivity2(view: View) { intent = Intent(view.context,Activity2::class.java) startActivity(intent) }

Теперь у вас есть функция, связанная с событием onClick вашей кнопки