我有一些片段以编程方式添加不同的标签。每个按钮都有一个带有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>
答案 0 :(得分:2)
让Fragment定义您的活动实现的接口。为该接口提供一个带有字符串参数的方法,并在onClick上传入当前Fragment的标记。
有关详细信息http://developer.android.com/training/basics/fragments/communicating.html
,请参阅有关片段通信的本指南