android-fragments 如何在片段中使用findViewById?

xkftehaa  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(160)

我是一个新的片段,我不能定义我的文本按钮等在我的片段,我不知道为什么,我已经尝试了getView()等,但没有工作,我也不知道什么东西应该去里面的CreateView或什么应该去上创建一切只是看起来真的很混乱。如果有人能帮助我,这将意味着很多,我已经尝试了一切,从youtube的堆栈溢出,谷歌!
我甚至不知道我是否正确地使用了mContext,onAttach方法。
P.S ive transferred eveyrthing from a Activity to a Fragment so i might have messed up where things go as i havent seen OnCreate View before.

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;

public class HomeFragment extends Fragment implements View.OnClickListener {

    private Context mContext;

    public String user_answer = "";
    public String name= "";
    public String current_answer = "";
    public int score = 0;
    public int current_question_num = 0;

    public HomeFragment() {

    }

    Random random = new Random();

    Button btnOption1, btnOption2, btnOption3, btnOption4;
    Button btnSubmit;
    TextView txtQuestion, txtScore;

    public MediaPlayer right, wrong;

    Questions questions = new Questions();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext=context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        right = MediaPlayer.create(mContext, R.raw.right);
        wrong =  MediaPlayer.create(mContext, R.raw.wrong);

        //TODO: GET NAME, SCORE FOR ALL FRAGMENTS

        init_textViews();

        gameLoop();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    public void init_textViews() {
        btnOption1 = (Button)getView().findViewById(R.id.btnOption1);
        btnOption2 = (Button)getView().findViewById(R.id.btnOption2);
        btnOption3 = (Button)getView().findViewById(R.id.btnOption3);
        btnOption4 = (Button)getView().findViewById(R.id.btnOption4);
        btnSubmit = (Button)getView().findViewById(R.id.btnSubmit);
        txtQuestion = (TextView) getView().findViewById(R.id.txtQuestion);
        txtScore = (TextView) getView().findViewById(R.id.txtScore);
    }

    public void gameLoop() {
        btnSubmit.setText("SUBMIT");

        init_textViews();

        if (current_question_num < questions.getCurrent_question().length) {

            set_answers_questions();

            btnOption1.setOnClickListener(this);
            btnOption2.setOnClickListener(this);
            btnOption3.setOnClickListener(this);
            btnOption4.setOnClickListener(this);
            btnSubmit.setOnClickListener(this);
            txtQuestion.setOnClickListener(this);

            btnSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    validateAnswer();
                }
            });

        } else {

            //TODO: MAKE IT GO TO THE LEADERBOARD FRAGMENT

        }

    }

    public void set_answers_questions() {
        btnOption1.setBackgroundColor(Color.rgb(109, 212, 126));
        btnOption2.setBackgroundColor(Color.rgb(109, 212, 126));
        btnOption3.setBackgroundColor(Color.rgb(109, 212, 126));
        btnOption4.setBackgroundColor(Color.rgb(109, 212, 126));

        String new_question = questions.getCurrent_question()[current_question_num].toString();
        txtQuestion.setText(new_question);

        int random_num1 = random.nextInt(questions.getAnswers()[current_question_num].length);
        btnOption1.setText(questions.getAnswers()[current_question_num][random_num1]);

        int random_num2 = random.nextInt(questions.getAnswers()[current_question_num].length);
        while (random_num2 == random_num1) {
            random_num2 = random.nextInt(questions.getAnswers()[current_question_num].length);
        }
        btnOption2.setText(questions.getAnswers()[current_question_num][random_num2]);

        int random_num3 = random.nextInt(questions.getAnswers()[current_question_num].length);
        while (random_num3 == random_num1 || random_num3 == random_num2) {
            random_num3 = random.nextInt(questions.getAnswers()[current_question_num].length);
        }
        btnOption3.setText(questions.getAnswers()[current_question_num][random_num3]);

        int random_num4 = random.nextInt(questions.getAnswers()[current_question_num].length);
        while (random_num4 == random_num1 || random_num4 == random_num2 || random_num4 == random_num3) {
            random_num4 = random.nextInt(questions.getAnswers()[current_question_num].length);
        }
        btnOption4.setText(questions.getAnswers()[current_question_num][random_num4]);

        current_answer = questions.getCorrect_answer()[current_question_num].toString();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btnOption1:
                btnOption1.setBackgroundColor(Color.GREEN);
                btnOption2.setBackgroundColor(Color.rgb(109, 212, 126));
                btnOption3.setBackgroundColor(Color.rgb(109, 212, 126));
                btnOption4.setBackgroundColor(Color.rgb(109, 212, 126));
                user_answer = btnOption1.getText().toString();
                break;
            case R.id.btnOption2:
                btnOption2.setBackgroundColor(Color.GREEN);
                btnOption1.setBackgroundColor(Color.rgb(109, 212, 126));
                btnOption3.setBackgroundColor(Color.rgb(109, 212, 126));
                btnOption4.setBackgroundColor(Color.rgb(109, 212, 126));
                user_answer = btnOption2.getText().toString();
                break;
            case R.id.btnOption3:
                btnOption3.setBackgroundColor(Color.GREEN);
                btnOption2.setBackgroundColor(Color.rgb(109, 212, 126));
                btnOption1.setBackgroundColor(Color.rgb(109, 212, 126));
                btnOption4.setBackgroundColor(Color.rgb(109, 212, 126));
                user_answer = btnOption3.getText().toString();
                break;
            case R.id.btnOption4:
                btnOption4.setBackgroundColor(Color.GREEN);
                btnOption2.setBackgroundColor(Color.rgb(109, 212, 126));
                btnOption3.setBackgroundColor(Color.rgb(109, 212, 126));
                btnOption1.setBackgroundColor(Color.rgb(109, 212, 126));
                user_answer = btnOption4.getText().toString();
                break;
            default:
                user_answer = "";
                break;
        }
    }

    public void validateAnswer() {
        if (user_answer.equals(current_answer)) {

            right.start();

            score++;

            if (!(btnOption1.getText().toString().equals(questions.getCorrect_answer()[current_question_num]))) {
                btnOption1.setBackgroundColor(Color.WHITE);
            }
            if (!(btnOption2.getText().toString().equals(questions.getCorrect_answer()[current_question_num]))) {
                btnOption2.setBackgroundColor(Color.WHITE);
            }
            if (!(btnOption3.getText().toString().equals(questions.getCorrect_answer()[current_question_num]))) {
                btnOption3.setBackgroundColor(Color.WHITE);
            }
            if (!(btnOption4.getText().toString().equals(questions.getCorrect_answer()[current_question_num]))) {
                btnOption4.setBackgroundColor(Color.WHITE);
            }

            txtScore.setText("Score: " + score);
            btnSubmit.setText("NEXT QUESTION");

            btnSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    current_question_num++;
                    gameLoop();
                }
            });

        } else {
            wrong.start();

            if (!(btnOption1.getText().toString().equals(questions.getCorrect_answer()[current_question_num]))) {
                btnOption1.setBackgroundColor(Color.WHITE);
            }
            if (!(btnOption2.getText().toString().equals(questions.getCorrect_answer()[current_question_num]))) {
                btnOption2.setBackgroundColor(Color.WHITE);
            }
            if (!(btnOption3.getText().toString().equals(questions.getCorrect_answer()[current_question_num]))) {
                btnOption3.setBackgroundColor(Color.WHITE);
            }
            if (!(btnOption4.getText().toString().equals(questions.getCorrect_answer()[current_question_num]))) {
                btnOption4.setBackgroundColor(Color.WHITE);
            }

            if (btnOption1.getText().toString().equals(user_answer)) {
                btnOption1.setBackgroundColor(Color.RED);
            } else if (btnOption2.getText().toString().equals(user_answer)) {
                btnOption2.setBackgroundColor(Color.RED);
            } else if (btnOption3.getText().toString().equals(user_answer)) {
                btnOption3.setBackgroundColor(Color.RED);
            } else if (btnOption4.getText().toString().equals(user_answer)) {
                btnOption4.setBackgroundColor(Color.RED);
            }

            btnSubmit.setText("NEXT QUESTION");
            btnSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    current_question_num++;
                    gameLoop();
                }
            });
        }
    }
}
fd3cxomn

fd3cxomn1#

在片段中配置视图

您在Fragment.onCreate(Bundle)中配置片段示例,但在public View onCreateView(LayoutInflater, ViewGroup, Bundle)中创建和配置片段的视图。
此方法用于扩大片段视图的布局,并将扩大的View返回到托管Activity。LayoutInflaterViewGroup参数是扩大布局所必需的。Bundle将包含此方法可用于从已保存状态重新创建视图的数据。
Fragment.onCreateView(…)中获取引用的工作方式与在Activity.onCreate(Bundle)中几乎相同。唯一的区别是在fragment的视图上调用View.findViewById(int)。之前使用的Activity.findViewById(int)方法是一个方便的方法,它在后台调用View.findViewById(int)。Fragment类没有相应的方便方法,所以必须调用真实的的方法。

演示代码

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
{
    View view = inflater.inflate(R.layout.id, container, false);
    Button mButton = view.findViewById(R.id.button_id);
    
    .
    .
    .

    return view;
}

相关问题