Android - 方法" ..."未定义类型Fragment

时间:2014-05-18 16:43:50

标签: java android android-fragments

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

我在哪里做错了?

这是我的片段类:

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);

    }

}

非常感谢你。

1 个答案:

答案 0 :(得分:1)

Activity中,newFragment被声明为Fragment。一个简单的Fragment没有changeText方法,或者你的子类的任何其他方法。

解决方案是将newFragment声明为fragment_corretto

fragment_corretto newFragment = new fragment_corretto();

PS。您应该遵循使用pascal case来命名类的约定。换句话说,请勿将其称为fragment_corretto,而是FragmentCorretto