fragment设置监听事件
·
分成多个fragment的目的就是分块操作,如果都在activity里面设置监听事件,代码数量较为庞大。
每一个fragment自己设置监听事件,条理更为清楚。
fragment的布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is fragment" />
</LinearLayout>
fragment的代码
public class Fragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button button1 = (Button) getActivity().findViewById(R.id.button1);
//监听button1单击事件
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_LONG).show();
}
});
//监听事件结束
}
}
更多推荐



所有评论(0)