【问题标题】:Android - Calling a function from a fragmentAndroid - 从片段调用函数
【发布时间】:2017-05-18 03:20:51
【问题描述】:

我正在尝试使用 3 个片段制作一个选项卡式活动。我的一个片段有一个按钮,它正在调用 onClick 函数:

<Button
    android:text="Start meeting"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="58dp"
    android:id="@+id/sp_live_meeting"
    android:layout_below="@+id/live_cost"
    android:layout_centerHorizontal="true"
    android:onClick="sp_timer" />

片段在对应的类文件中创建:

public class LiveMeeting_meeting_fragment extends Fragment {

Button sp;
Button stop;
Chronometer chrono;
int cnt = 0;
long timeStop;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.livemeeting_meeting_fragment, container, false);
    sp = (Button) rootView.findViewById(R.id.sp_live_meeting);
    stop = (Button) rootView.findViewById(R.id.stop_live_meeting);
    chrono = (Chronometer) rootView.findViewById(R.id.live_timer);
    return rootView;
}

public void sp_timer(View view){
    if(cnt == 0){
        sp.setText("Pause meeting");
        chrono.setBase(SystemClock.elapsedRealtime() + timeStop);
        chrono.start();
        cnt = 1;
    } else if (cnt == 1){
        sp.setText("Continue meeting");
        chrono.stop();
        timeStop = chrono.getBase() - SystemClock.elapsedRealtime();
        cnt = 0;
    }

}
}

我现在的问题是,我无法调用该函数,因为它告诉我它找不到该函数:

java.lang.IllegalStateException: Could not find method sp_timer(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'sp_live_meeting'

我该如何解决这个问题?

【问题讨论】:

  • 不要使用 onClick 属性。它只能用于活动。使用View#setOnClickListener()手动设置点击方式。

标签: java android xml android-fragments


【解决方案1】:

从 XML 中删除您的 onClick 属性,改为使用 onClickListener

代码:

Button btn = (Button) findViewById(R.id.mybutton);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //write your sp_timer method here
    }
});

Android 仅在当前 Activity 中查找 onClick 方法 sp_timer()。如果您正在使用片段,请务必记住这一点,因为即使您使用片段添加上面的 XML,Android 也不会在用于添加 XML 的片段的 .java 文件中查找 onClick 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-07
    • 2019-01-05
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    相关资源
    最近更新 更多