繁体   English   中英

Android-未为Fragment类型定义方法“…”

[英]Android - The method “…” is undefined for the type Fragment

我在片段类内部创建了一个名为“ changeText”的方法,该方法将在创建片段后立即更改该片段的两个TextView。 问题是我无法从我的活动中调用方法“ changeText”,因为我收到错误消息“对于类型Fragment,未定义方法changeText(String [])”,就像它不存在一样。

我在哪里做错了?

这是我的片段类:

package com.example.quizone_2;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class fragment_corretto extends Fragment {

TextView questionTv, answerTv;

public fragment_corretto() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_corretto, container,
            false);

    questionTv = (TextView)rootView.findViewById(R.id.question);
    answerTv = (TextView)rootView.findViewById(R.id.answer);

    return rootView;
}

public void changeText(String[] text){
    questionTv.setText(text[1]);
    answerTv.setText(text[0]);
}

}

这是我的活动文件中的方法,在这里我将其称为changeText方法:

public void answerTrue(View view){

    if(info[2] == "1"){

        // Create new fragment and transaction
        Fragment newFragment = new fragment_corretto();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.container, newFragment);

        // Commit the transaction
        transaction.commit();

        newFragment.changeText(info);

    }else{

        // Create new fragment and transaction
        Fragment newFragment = new Fragment_sbagliato();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.container, newFragment);

        // Commit the transaction
        transaction.commit();

                    newFragment.changeText(info);

    }

}

提前非常感谢您。

在您的ActivitynewFragment被声明为Fragment 一个简单的Fragment没有changeText方法或子类的其他任何方法。

解决方案是将newFragment声明为fragment_corretto

fragment_corretto newFragment = new fragment_corretto();

PS。 您应遵循使用pascal大小写命名类的约定。 换句话说,不要将其命名为fragment_corretto ,而是将其命名为FragmentCorretto

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM