Фрагменты с текстовыми представлениями и кнопками - PullRequest
0 голосов
/ 10 июля 2020

Привет, я хочу иметь кнопку, отображающую новый вопрос в текстовом представлении, и я использую фрагменты. Делал курс udacity, и теперь он работает, когда вы щелкаете текстовый вопрос, но возникают проблемы с реализацией кнопки. Можно ли это вообще сделать? или для этого вам нужно писать более сложные части кода? Я попытался реализовать кнопку во фрагменте, и когда я запускаю приложение, оно доступно для нажатия, но не запускает метод onClick (). Спасибо

Вот мой фрагмент

public class QuestionFragment extends Fragment {


    // Final Strings to store state information about the list of images and list index
    public static final String QUESTION_ID_LIST = "question_ids";
    public static final String LIST_INDEX = "list_index";

    private final String TAG = getClass().getSimpleName();
    private List<Integer> mQuestionIds;
    private int mListIndex;
 

    public QuestionFragment() {
    }

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

        // Load the saved state (the list of images and list index) if there is one
        if (savedInstanceState != null) {
            mQuestionIds = savedInstanceState.getIntegerArrayList(QUESTION_ID_LIST);
            mListIndex = savedInstanceState.getInt(LIST_INDEX);
        }
            //Inflate the fragment layout
            View rootView = inflater.inflate(R.layout.fragments_question, container, false);

            //Get a reference to the textView in the fragment layout
            final TextView textView = (TextView) rootView.findViewById(R.id.fragment_question);

            View questionView = inflater.inflate(R.layout.fragment_question, container, false);
            final Button next =  questionView.findViewById(R.id.nextQuestion);




            //if list of questions exists set the question resource to the correct item
            //Otherwise create a log statement to indicate list was not found
            if (mQuestionIds != null) {
                textView.setText(mQuestionIds.get(mListIndex));

                //Set n on Click Listener to the button
                rootView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    Log.d(TAG, "Button pressed");

                        //Increment the position in the question lisy as long as index is less than list length
                        if (mListIndex < mQuestionIds.size() - 1) {
                            mListIndex++;
                        } else {
                            //end of questions reached
                            textView.setText("End of questions");
                        }
                        //Set the text resource to display the list item at that stored index
                        textView.setText(mQuestionIds.get(mListIndex));
                    }
                });
            } else {
                //Log message that list is null
                Log.d(TAG, "No questions left");
            }

            //return root view
            return rootView;

        }


        public void setmQuestionIds (List < Integer > mQuestionIds) {
            this.mQuestionIds = mQuestionIds;
        }

        public void setmListIndex ( int mListIndex){
            this.mListIndex = mListIndex;
        }

    /**
     * Save the current state of this fragment
     */
    @Override
    public void onSaveInstanceState(Bundle currentState) {
        currentState.putIntegerArrayList(QUESTION_ID_LIST, (ArrayList<Integer>) mQuestionIds);
        currentState.putInt(LIST_INDEX, mListIndex);
    }
}

Вот мое основное занятие

public class Questions extends AppCompatActivity {

    Button next;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_question);


        // Only create new fragments when there is no previously saved state
        if (savedInstanceState == null) {
            //Create Question Fragment
            QuestionFragment questionFragment = new QuestionFragment();

            //set the list of question Ids for the head fragent and set the position to the second question
            questionFragment.setmQuestionIds(QuestionList.getQuestions());
            questionFragment.setmListIndex(1);
            //Fragment manager and transaction to add this fragment
            FragmentManager fragmentManager = getSupportFragmentManager();

            //Fragment transaction
            fragmentManager.beginTransaction()
                    .add(R.id.question_container, questionFragment)
                    .commit();
        }
    }
}

Мой фрагмент xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fragment_question_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".Questions"
   >

    <FrameLayout
        android:id="@+id/question_container"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:background="@color/colorBackground"
        android:scaleType="centerInside">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/nextQuestion"/>

    </FrameLayout>

</LinearLayout>

И главное активность xml

<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:id="@+id/fragment_question"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="320dp"
    android:textAlignment="center"
    android:gravity="center">

</TextView>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...