繁体   English   中英

如何从它的按钮的xml onClick视图中识别片段?

[英]How to identify a fragment from it's button's xml onClick view?

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

NewFragment.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;
}

Activity.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>

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

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

暂无
暂无

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

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