如何创建片段交互?

时间:2017-10-23 11:01:58

标签: android android-fragments

这些是我对片段类的导入。

import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

正在初始化的类

public class FragmentDemo extends Fragment {

公共构造函数为空,必须保持这种状态

public FragmentDemo() {
    }

必须附加到活动,界面取决于所述活动

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

片段

的通胀布局
        View result = inflater.inflate(R.layout.fragment_fragment_demo, container, false);

        TextView textView = (TextView)result.findViewById(R.id.textView2);
        Button button = (Button)result.findViewById(R.id.button2);

        textView.setText("HEY, THIS IS A TEST!");
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Log.e("FRAGMENT", "BUTTON IS WORKING!");
                // why no toast?
            }
        });

        return result;
    }

}

3 个答案:

答案 0 :(得分:1)

您必须创建两个类以使其更清晰,一个用于片段的交互,另一个用于主类。

第一个应该是这样的:

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Text;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link InteractionFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link InteractionFragment#newInstance} factory method to
 * create an instance of this fragment.
 */

public class InteractionFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_NAME = "name";
    private static final String ARG_LAST_NAME = "lastName";

    // TODO: Rename and change types of parameters
    private String name;
    private String lastName;

    private OnFragmentInteractionListener mListener;

    public InteractionFragment() {
        // 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 InteractionFragment.
     */
    // TODO: Rename and change types and number of parameters
    // Factory method
    public static InteractionFragment newInstance(String param1, String param2) {
        InteractionFragment fragment = new InteractionFragment();
        Bundle args = new Bundle();
        args.putString(ARG_NAME, param1);
        args.putString(ARG_LAST_NAME, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            name = getArguments().getString(ARG_NAME);
            lastName = getArguments().getString(ARG_LAST_NAME);
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View v = inflater.inflate(R.layout.fragment_interaction, container, false);
        TextView nameText = (TextView)v.findViewById(R.id.name);
        TextView lastNameText = (TextView)v.findViewById(R.id.last_name);

        nameText.setText(name);
        lastNameText.setText(lastName);

        Button button = (Button)v.findViewById(R.id.button3);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mListener.somethingHappened("THE BUTTON WAS PRESSED, HOW EXCITING!");
            }
        });
        return v;
    }

    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

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

    public void printALog(){
        Log.wtf("PRINTING", "ITS WORKING!");
    }

    /**
     * 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 {
        void somethingHappened(String message);
    }
}

虽然第二个应该是这样的:

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.TransactionTooLargeException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements InteractionFragment.OnFragmentInteractionListener {

    InteractionFragment fragment;

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

    private void addFragment(Fragment f){

        // add a fragment through code
        // fragment manager - the guy in charge of any fragment related logic
        FragmentManager manager = getFragmentManager();


        // transactions
        FragmentTransaction transaction = manager.beginTransaction();

        // actually do the thing
        //fragment = InteractionFragment.newInstance("Juan","Perez");
        // 3rd parameter - fragment
        transaction.add(R.id.container, f, "dude");
        transaction.commit();
    }

    @Override
    public void somethingHappened(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    public void doSomethingOnFragment(View v){
        fragment.printALog();
    }

    public void swapFragments(View v){

        FragmentManager manager = getFragmentManager();


        Fragment f = manager.findFragmentByTag("dude");

        if(f != null){
            Toast.makeText(this, "FRAGMENT BEING REMOVED", Toast.LENGTH_SHORT).show();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.remove(f);
            transaction.commit();
        } else {

            Toast.makeText(this, "NO FRAGMENT TO REMOVE", Toast.LENGTH_SHORT).show();
        }
    }

    public void addFragment1(View v){
        fragment = InteractionFragment.newInstance("Juan","Perez");
        addFragment(fragment);
    }

    public void addFragment2(View v){
        FragmentDemo fd = new FragmentDemo();
        addFragment(fd);
    }
}

答案 1 :(得分:0)

我不确定你的问题究竟是什么,所以我先假设你的问题与你的“为什么不敬酒?”有关。评论。 问题是你正在使用日志功能,这在logcat控制台中打印,而不是通过toasts。 如果要显示祝酒词,请使用

Toast.makeText(context, text, durationInMs).show();

因为你在片段中,所使用的上下文是activity,它有这个片段,所以我们使用getActivity()获取上下文。因此Toast将是:

Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();

答案 2 :(得分:0)

我不确定你的问题究竟是什么,所以我先假设你的问题与你的“为什么不敬酒?”有关。评论。 问题是你正在使用日志功能,这在logcat控制台中打印,而不是通过toasts。 如果要显示祝酒词,请使用

Toast.makeText(context, text, durationInMs).show();

更多信息here