Fragment中Button的android:onClick 无法监听相应
在Fragment的布局文件中,Button控件下添加android:onClick监听;
1.fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.jjc.demo.MainActivity$PlaceholderFragment" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello_world" android:onClick="button" /> </RelativeLayout>
2.MainActivity.java
package com.jjc.demo; import android.support.v7.app.ActionBarActivity; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } } public void button(View v){ Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show(); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); } private void initView() { } } }
经测试 需要在Fragment的父Activity,实现
public void button(View v){ Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show(); }
才能监听到Button的点击事件,在Fragment中则会报错。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。