0

我有一些片段正在以不同的标签以编程方式添加。每个都有一个带有 xml onClick 的按钮,该按钮被传递一个视图。如何确定从该视图中单击了哪个片段?代码如下。

新片段.java

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

    TextView tv = (TextView) view.findViewById(R.id.name);
    Bundle bundle = this.getArguments();
    int index = bundle.getInt("index");
    tv.setText(Integer.toString(index));

    return view;
}

活动.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);

    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();

    for (int loop = 0; loop < 4; loop++) {
        NewFragment fragment = new NewFragment();
        Bundle args = new Bundle();
        args.putInt("index", loop);
        fragment.setArguments(args);
    //tag set to value of loop here
        ft.add(R.id.new_fragment, fragment, Integer.toString(loop));
    }
    ft.commit();
}

public void toggleEdit(View view) {
  //How do I find clicked fragment?
  }

new_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/test">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:layout_marginLeft="5dp"
            android:padding="5dp"
            />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/name"
            android:text="Test"
        />
    </LinearLayout>
    <!-- Button in question is below -->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="@string/edit"
        android:onClick="toggleEdit"
        android:id="@+id/edit_button"
    />

</LinearLayout>
4

1 回答 1

2

让您的 Fragment 定义您的活动实现的接口。给该接口一个带有字符串参数的方法,然后 onClick,传入当前 Fragment 的标签。

有关更多详细信息,请参阅片段通信指南http://developer.android.com/training/basics/fragments/communicating.html

于 2013-11-07T19:09:41.723 回答