片段重叠另一个片段而不是替换它

时间:2016-05-03 22:55:12

标签: java android android-fragments

我的设置是一个main_activity片段,只有欢迎文本,当你点击开始按钮时,它应该切换片段。它不是替换当前片段,而是将其覆盖在main_activity片段之上,并且不允许我执行与新片段相关联的操作。

Main Activity example

quote_fragment overlapping main activity

activity_main.xml中:

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_activity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="false"
    android:contextClickable="false"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="me.alexoladele.quotebook.MainActivity">

    <TextView
        android:id="@+id/welcome_screen_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|top"
        android:layout_marginTop="144dp"
        android:gravity="center"
        android:text="@string/welcome_screen_text"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="36sp" />

    <Button
        android:id="@+id/start_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|bottom"
        android:layout_marginBottom="47dp"
        android:clickable="true"
        android:enabled="true"
        android:text="@string/start_button" />
</FrameLayout>

ActivityMain.java

package me.alexoladele.quotebook;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    int count = 0;
    final QuoteFragment quoteFragment = new QuoteFragment();

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


        final Button startButton = (Button) findViewById(R.id.start_button);
        final TextView welcomeText = (TextView) findViewById(R.id.welcome_screen_text);
        if (startButton != null)
            startButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startSecondFragment(); // start your fragment from MainActivity
                    //startButton.setVisibility(v.GONE);
                    //welcomeText.setVisibility(v.GONE);
                }
            });


    }

    // This method will be in charge of handling your second fragment
    private void startSecondFragment() {
        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction()
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .replace(R.id.main_activity, quoteFragment)
                .commit();



    }


}

quote_fragment.xml:

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/quote_frag"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:contextClickable="true">

    <TextView
        android:id="@+id/quote"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:fontFamily="sans-serif-medium"
        android:gravity="center"
        android:text="@string/tap_screen"
        android:textColor="#a6a6a6"
        android:textSize="26sp" />

    <TextView
        android:id="@+id/person"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|bottom"
        android:fontFamily="sans-serif-medium"
        android:gravity="center"
        android:text="@string/quotist_name"
        android:textColor="#585858"
        android:textSize="26sp"
        android:visibility="visible" />

</FrameLayout>

QuoteFragment.java:

package me.alexoladele.quotebook;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//import android.support.v4.app.Fragment;

public class QuoteFragment extends android.support.v4.app.Fragment {
    int count = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.quote_fragment,container, false);

        FrameLayout touch = (FrameLayout) v.findViewById(R.id.main_activity);
        final TextView quoteText = (TextView) v.findViewById(R.id.quote);


        // Makes quotes array
        //region Description
        String[] quotes = {
                (Quotes go here, but I didn't put them here to save space)
        };
        //endregion

        // Put quotes array into arraylist
        final List<String> quoteList = new ArrayList<>(Arrays.asList(quotes));

        //
        if (touch != null)
            touch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (count >= quoteList.size()) {
                        count = 0;
                    }
                    Quote q = new Quote("");
                    q.setQuote(quoteList.get(count));

                    quoteText.setText(q.getQuote());
                    count++;

                    v.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            return true;
                        }
                    });

                }
            });



        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.quote_fragment, container, false);
    }




}

welcome_screen_fragment:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    tools:context="me.alexoladele.quotebook.WelcomeScreen">

    <TextView
        android:id="@+id/welcome_screen_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|top"
        android:layout_marginTop="144dp"
        android:gravity="center"
        android:text="@string/welcome_screen_text"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="36sp" />

    <Button
        android:id="@+id/start_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|bottom"
        android:layout_marginBottom="47dp"
        android:clickable="true"
        android:enabled="true"
        android:text="@string/start_button" />

</FrameLayout>

WelcomeScreen.java:

package me.alexoladele.quotebook;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link WelcomeScreen.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link WelcomeScreen#newInstance} factory method to
 * create an instance of this fragment.
 */
public class WelcomeScreen extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    //private OnFragmentInteractionListener mListener;

    public WelcomeScreen() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment WelcomeScreen.
     */
    // TODO: Rename and change types and number of parameters
    public static WelcomeScreen newInstance(String param1, String param2) {
        WelcomeScreen fragment = new WelcomeScreen();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.welcome_screen_fragment, container, false);
    }

   /* // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    *//**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     *//*
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }*/
}

1 个答案:

答案 0 :(得分:1)

请勿替换顶级视图组。在顶层框架布局内创建一个空框架布局,并将其用作要替换的ID。

如果您在主布局中有元素,您不再需要隐藏它们(或者使用片段在首先显示它们将被替换)。