如何让重复的片段得到他们的个人布局?

时间:2016-05-15 02:47:18

标签: java android android-fragments

我试图制作一个终极的TicTacToe游戏,这需要同时运行同一个片段的9个实例。我把它们放在另一个可以控制它们的片段中。执行其他任务时。

我试图想出一种方法来管理每个片段,让它们相互交谈,并知道它们是谁。 (基本上存储它的行和col,也许允许大布局运行一些方法)有没有办法做到这一点?我对片段管理器没有多少经验,但我没有交换任何东西,这对于这么简单的任务来说似乎有很多工作。

大片段          

    <LinearLayout
        android:id="@+id/ll_Big_Row_0"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:baselineAligned="false" >

        <fragment
            android:id="@+id/board_0x0"
            android:name="com.example.tictactectoe.Fragment_Small_Board"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="5dp"
            android:layout_weight="1" />

        <fragment
            android:id="@+id/board_0x1"
            android:name="com.example.tictactectoe.Fragment_Small_Board"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="5dp"
            android:layout_weight="1" />
        ....
    <LinearLayout/>
    ....
  <LinearLayout/>

smallFragment.java

public class Fragment_Small_Board extends Fragment {

    private int thisRow = 0;
    private int thisCol = 0;

    private ImageButton square0x0;
    private ImageButton square0x1;
    ...

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

        setUpButtons(view);
        buttonOnclickListeners();

        return view;
    }

    public void setUpButtons(View view){
       square0x0 = (ImageButton) view.findViewById(R.id.small_0_0);
       square0x1 = (ImageButton) view.findViewById(R.id.small_0_1);
       ....
    }

    public void buttonOnclickListeners(){
        square0x0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                validateMove();
                square0x0.setBackgroundResource(backgroundID);
                square0x0.setImageResource(pictureID);
            }
        });
       ....
    }

1 个答案:

答案 0 :(得分:0)

不要在父片段中放置9个片段,因为在您的情况下,它看起来并不必要。所以你可以做的是在你的活动中添加这九个片段。并为每个片段提供通信器(接口),以便它们可以通过活动相互通信。

要添加片段,请执行以下操作

    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    fragment =new MyFragment();
    ft.add(android.R.id.content,fragment,"myFragmentTag");
    ft.commit();

并根据您的功能继续更换碎片。

This link will give you brief idea about how to set up communicator inside fragment and extend it in your activity