簡體   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