首页 > 代码库 > Fragment中Button的android:onClick 无法监听相应
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中则会报错。
Fragment中Button的android:onClick 无法监听相应
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。