简体   繁体   English

动态地在单个活动中实现多个片段

[英]Implementing multiple fragments in a single activity Dynamically

I am working on fragments 我正在研究碎片


Use case i am trying to implement :: 用例我试图实现 ::

  • I am using dynamic fragments 我正在使用动态片段
  • I am using three fragments in a single activity 我在一个活动中使用三个片段
  • my goal is to communicate between all the three fragments 我的目标是在所有三个片段之间进行通信
  • I am using support package for fragments 我正在使用片段支持包

Each fragment has a single widget 每个片段都有一个小部件

  • my_fragment1 has edittext my_fragment1edittext
  • my_fragment2 has button my_fragment2button
  • my_fragment3 has TextView my_fragment3TextView

On click of button the text from the edittext must be displayed in the textview 单击buttonedittext的文本必须显示在textview


What i have tried so far i have constructed most of the scenario below 到目前为止,我已经尝试过构建下面的大部分场景


Top_Fragment.java Top_Fragment.java

public class Top_Fragment extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        View view=inflater.inflate(R.layout.my_fragment1, container, false);

        return view;
    }
}

Middle_Fragment.java Middle_Fragment.java

package com.example.deleteme;

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

public class Middle_Fragment extends Fragment{

    View view;
    Button btn;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        view=inflater.inflate(R.layout.my_fragment2, container, false);
        btn=(Button) view.findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub



            }
        });
        return view;
    }
}

Bottom_Fragment.java Bottom_Fragment.java

public class Bottom_Fragment extends Fragment{

    View view;
    TextView display_text;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        view=inflater.inflate(R.layout.my_fragment3, container,false);
        display_text=(TextView) view.findViewById(R.id.editText1);
        return view;
    }

    public void setName(String Name){
        display_text.setText("Result::" + Name);
    }



}

MainActivity.java MainActivity.java

public class MainActivity extends FragmentActivity {

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

        Top_Fragment frg=new Top_Fragment();//create the fragment instance for the top fragment
        Middle_Fragment frg1=new Middle_Fragment();//create the fragment instance for the middle fragment
        Bottom_Fragment frg2=new Bottom_Fragment();//create the fragment instance for the bottom fragment

        FragmentManager manager=getSupportFragmentManager();//create an instance of fragment manager

        FragmentTransaction transaction=manager.beginTransaction();//create an instance of Fragment-transaction

        transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
        transaction.add(R.id.My_Container_2_ID, frg1, "Frag_Middle_tag");
        transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");


        transaction.commit();

    }


}

activity_main.xml activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity" 
    android:background="@color/black">

    <FrameLayout
        android:id="@+id/My_Container_1_ID"
        android:layout_width="fill_parent"
        android:layout_height="150dp" 
        android:background="@color/yellow">
    </FrameLayout>

    <FrameLayout
        android:id="@+id/My_Container_2_ID"
        android:layout_width="fill_parent"
        android:layout_height="150dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/My_Container_1_ID"
        android:background="@color/Orange" >
    </FrameLayout>

    <FrameLayout
        android:id="@+id/My_Container_3_ID"
        android:layout_width="fill_parent"
        android:layout_height="150dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/My_Container_2_ID"
        android:background="@color/purple" >
    </FrameLayout>

</RelativeLayout>

my_fragment1.xml my_fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/green" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:ems="10"
        android:textColor="#000000"
        android:singleLine="true" >

        <requestFocus />
    </EditText>

</RelativeLayout>

my_fragment2.xml my_fragment2.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:background="@color/pink">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@color/black"
        android:text="Button"
        android:textColor="#FFFFFF" />

</RelativeLayout>

my_fragment3.xml my_fragment3.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="30dp" />

</RelativeLayout>

My output is Like below :: 我的输出如下

在此输入图像描述


What I am having problem in achieving :: 我遇到的问题是什么 ::

  • I am not able to set the value obtained from edit text to textview on click of the button 单击button我无法将从edit text获得的值设置为textview

Any Ideas? 有任何想法吗?

All Fragment-to-Fragment communication is done through the associated Activity. 所有Fragment-to-Fragment通信都是通过相关的Activity完成的。 Two Fragments should never communicate directly. 两个碎片永远不应该直接通信。

http://developer.android.com/training/basics/fragments/communicating.html http://developer.android.com/training/basics/fragments/communicating.html

test.java // in your case its MainActivity test.java //在你的情况下是它的MainActivity

public class test extends FragmentActivity implements textEntered {

    String value;
    boolean check = false;
    BottomFragment frg2;
    FragmentTransaction transaction;

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

        Top_Fragment frg = new Top_Fragment();
        frg2 = new BottomFragment();

        FragmentManager manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
        transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");
        transaction.commit();
    }

    @Override
    public void setValue(String editextvalue) {
        value = editextvalue;
        if (frg2 != null) {
            frg2.setName(value);
        } else {
            Toast.makeText(getApplicationContext(), "fragment 2  is null", 1000).show();
        }
    }

}    

Top_Fragment.java

public class Top_Fragment extends Fragment {
    textEntered mCallback;
    Button b;
    EditText ed;

    public interface textEntered {
        public void setValue(String editextvalue);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        View view = inflater.inflate(R.layout.my_fragment1, container, false);
        ed = (EditText) view.findViewById(R.id.editText1);


        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        b = (Button) getView().findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String s = ed.getText().toString();
                mCallback.setValue(s);
            }

        });
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (textEntered) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() +
                " must implement textEntered");
        }
    }
}

my_fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:ems="10"
        android:textColor="#000000"
        android:singleLine="true" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Button" />

</RelativeLayout>

Change to 改成

 display_text=(TextView) view.findViewById(R.id.textView1);
 // id is textView 1 not editText1

in BottomFragment 在BottomFragment中

snap

在此输入图像描述

Communication between Fragments 碎片之间的通信

There can be many scenarios where communication between fragment is required. 可能存在许多需要片段之间的通信的场景。 You need to pass data between fragments on button click event. 您需要在按钮单击事件的片段之间传递数据。 You may also use Android toolbar to switch between fragments. 您也可以使用Android工具栏在片段之间切换。 When you add buttons to your toolbar, you need to dynamically change screen using fragment. 向工具栏添加按钮时,需要使用片段动态更改屏幕。

Create an interface which will help us to communicate 创建一个有助于我们沟通的界面

Communicate.java Communicate.java

package com.example.amaanmemon.testfragment;

interface Communicate {
 public void sendData();
}

TopFragment.java TopFragment.java

package com.example.amaanmemon.testfragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class TopFragment extends Fragment {

EditText  firstName;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // TODO Auto-generated method stub

    View view=inflater.inflate(R.layout.my_fragment1, container, false);
    return view;
}

public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    firstName = (EditText) getActivity().findViewById(R.id.editText1);
}

public String getData(){
    return firstName.getText().toString();
}
}

MiddleFragment.java MiddleFragment.java

package com.example.amaanmemon.testfragment;

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

public class MiddleFragment extends Fragment implements OnClickListener{

View view;
Button btn;
Communicate cm;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    view=inflater.inflate(R.layout.my_fragment2, container, false);
    return  view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    cm = (Communicate) getActivity();
    btn = (Button) getActivity().findViewById(R.id.button1);
    btn.setOnClickListener(this);
}

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    cm.sendData();
}
}

BottomFragment.java BottomFragment.java

package com.example.amaanmemon.testfragment;

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

public class BottomFragment extends Fragment{

int count;
View view;
TextView display_text;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    view=inflater.inflate(R.layout.my_fragment3, container,false);
    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    display_text = (TextView)getActivity().findViewById(R.id.textView1);
}

public void incrementData(String displayText){
    display_text.setText(displayText);
}
}

MainActivity.java MainActivity.java

package com.example.amaanmemon.testfragment;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class MainActivity extends FragmentActivity implements Communicate{

TopFragment frg;
MiddleFragment frg1;
BottomFragment frg2;
FragmentTransaction transaction;

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

    frg = new TopFragment();
    frg1 = new MiddleFragment();
    frg2 = new BottomFragment();

    FragmentManager manager=getSupportFragmentManager();
    transaction=manager.beginTransaction();
    transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
    transaction.add(R.id.My_Container_2_ID, frg1, "Frag_Middle_tag");
    transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");
    transaction.commit();
}

@Override
public void sendData() {
    String temp = frg.getData();
    frg2.incrementData(temp);
}
}

You can copy xml files from question. 您可以从问题中复制xml文件。 you can watch the output below. 你可以看下面的输出。

产量

You can use the Activity for that. 你可以使用Activity。

in the onClick of the bottom fragment you can do something like 在底部片段的onClick中你可以做类似的事情

((MainActivity) getActivity()).doIt();

And make a method doIt in your MainActivity maybe something like this 并作出方法doItMainActivity也许是这样的

public void doIt(){
    frg2.setName(frg.getText())
}

and in the top fragment make a method getText that returns the text of the EditText 并在顶部片段中创建一个方法getText ,它返回EditText的文本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM