0

Пытаюсь добавить фрагмент fragment_new.xml нажатием кнопки в активности.

MainActivity.java:

package com.mrdryn.fragmenttest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment = new NewFragment();
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.add(R.layout.fragment_new, fragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        });
        }
}

activity_main.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:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mrdryn.fragmenttest.MainActivity">


    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="84dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />
</android.support.constraint.ConstraintLayout>

NewFragment.java:

package com.mrdryn.fragmenttest;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import java.util.Date;

/**
 * Created by zxc on 24.08.2017.
 */

public class NewFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle SavedInstanceState){
        View view = inflater.inflate(R.layout.fragment_new, container, false);
        Button button = (Button)view.findViewById(R.id.button);
        final TextView txtx = (TextView)view.findViewById(R.id.textView);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String curDate = new Date().toString();
                txtx.setText(curDate);
            }
        });
        return view;
    }
}

fragment_new.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:id="@+id/fragmentLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="359dp"
        android:layout_height="50dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="100dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
1
  • Ошибка java.lang.IllegalArgumentException: No view found for id 0x7f0b0060 (com.mrdryn.fragmenttest:id/fragmentLayout) for fragment NewFragment{46aff4d #0 id=0x7f0b0060}
    – mrdryn
    1 сен 2017 в 17:57

2 ответа 2

1

Согласно ошибке система не смогла найти в разметке активити элемент с указанным вами ID. Вы должны указывать ID контейнера, в который надо добавить фрагмент, а не его разметку. Т.е., например, передавайте ID основного контейнера R.id.mainLayout, вместо R.layout.fragment_new.

Возможно имеет смысл добавить в разметку активити специальный контейнер для фрагмента, чтобы он не перекрывал вашу кнопку.

2
  • Спасибо. А мне и нужно чтобы фрагмент перекрывал активность полностью, только получается что фрагмент "прозрачный" и через него видны и нажимаются кнопки в активности.
    – mrdryn
    2 сен 2017 в 10:21
  • Просто задайте непрозрачный фон фрагмент в его разметке
    – ЮрийСПб
    2 сен 2017 в 10:51
0

В разметку активности необходимо добавить FrameLayout в качестве контейнера для фрагмента

 <FrameLayout
                android:id="@+id/fragment_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"/>

В активити пишем `fragmentTransaction.add(R.id.fragment_container, fragment);

После проделанных операция всё должно заработать =)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.