-1

После добавления RecyclerView в Layout активности он стал отображаться на половину.

Activity xml:

    <?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GameActivity">

    <LinearLayout
        android:id="@+id/questionLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="10dp"
        android:background="#77B4CE"
        android:gravity="center|center_horizontal|top"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:id="@+id/questionTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/dummy_content"
            android:textSize="36sp" />

        <ProgressBar
            android:id="@+id/questionCountdownProgressBar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="25dp" />
    </LinearLayout>


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/answersView"
        android:layout_below="@id/questionLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginBottom="0dp"
        android:padding="0dp"
        android:scrollbars="horizontal" />


</RelativeLayout>

Item xml:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="0dp"
    android:layout_margin="0dp"
    >

    <TextView
        android:id="@+id/questionTextView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="20sp"/>


</LinearLayout>

MainActivity code

 public class GameActivity extends AppCompatActivity {
    ProgressBar progressBar;
    QuestionDatabase database;
    RecyclerView recyclerView;
    SelectQuestionRecycleViewAdapter rAdapter;
    GridLayoutManager rLayoutManager;
    CountDownTimer current;
    List<Question> testList;
    View questTextV;
    int time = 45000;
    int interval = 500;
    int delta = (int) (100/((time)/interval));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        database = QuestionDatabase.getDatabase(this);
        QuestionDAO dao = database.dao();
        testList = dao.getAll();
        setContentView(R.layout.activity_game);
        recyclerView = findViewById(R.id.answersView);
        rLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(rLayoutManager);
        rAdapter = new SelectQuestionRecycleViewAdapter(testList.get(0));
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, rLayoutManager.getOrientation()));
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(rAdapter);
        questTextV = findViewById(R.id.questionTextView);
        questTextV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            nextQuestion();
            }
        });
        progressBar = findViewById(R.id.questionCountdownProgressBar);
        progressBar.setProgress(100);
    }
    private void nextQuestion() {//TEST CODE
        Log.d("DELTA", ""+delta);
        int a = (int) (Math.random()*testList.size());
        ((TextView) (questTextV)).setText(testList.get(a).text);
        rAdapter.setAnswers(testList.get(a));
        if(current != null)
            current.cancel();
        progressBar.setProgress(100);
        current =  new CountDownTimer(time, interval) {
            @Override
            public void onTick(long millisUntilFinished) {
                progressBar.setProgress(progressBar.getProgress() - delta);
                Log.e("Countdown: ", "" + millisUntilFinished / 1000 + " " + System.currentTimeMillis() / 1000);
            }
            @Override
            public void onFinish() {
                nextQuestion();
                Log.e("Countdown_finished: ", " " + System.currentTimeMillis() / 1000);
            }
        }.start();
    }
}

Adapter code

    public class SelectQuestionRecycleViewAdapter extends RecyclerView.Adapter<SelectQuestionRecycleViewAdapter.QuestionViewHolder> {

    private ArrayList<String> answers;

    @NonNull
    @Override
    public QuestionViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_question_layout, parent, false);
        QuestionViewHolder questionViewHolder = new QuestionViewHolder(v);
        return questionViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull QuestionViewHolder holder, int position) {

        holder.textView.setText(answers.get(position));

    }

    @Override
    public int getItemCount() {
        return answers.size();
    }

    class QuestionViewHolder extends RecyclerView.ViewHolder{

        public TextView textView;

        public QuestionViewHolder(@NonNull View view) {
            super(view);
            textView = view.findViewById(R.id.questionTextView);
        }
    }

    public SelectQuestionRecycleViewAdapter(Question question) {
        this.answers = new ArrayList<>(4);
        inflateAnswers(question);
    }


    private void inflateAnswers(Question q){

        answers.add(q.correctAnswer);
        answers.add(q.answer1);
        answers.add(q.answer2);
        answers.add(q.answer3);

    }

    public void setAnswers(Question question){

        answers.clear();
        inflateAnswers(question);
        notifyDataSetChanged();

    }
}

3
  • Добро пожаловать на stackoverflow на русском. Тут принято задавать вопросы на русском языке.
    – Denis640Kb
    15 янв 2020 в 19:06
  • Спасибо, исправил. 15 янв 2020 в 19:09
  • У вас все размеры для слоев по высоте match_parent - конечно у вас будут наложения. 16 янв 2020 в 9:58

2 ответа 2

0

Попробуйте следующий пример:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GameActivity">

    <LinearLayout
        android:id="@+id/questionLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#77B4CE"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="10dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/questionTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Эйййййййййййй"
            android:textSize="36sp" />

        <ProgressBar
            android:id="@+id/questionCountdownProgressBar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="25dp" />
    </LinearLayout>


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/answersView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_below="@id/questionLayout"
        android:padding="0dp"
        android:scrollbars="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/questionLayout" />


</androidx.constraintlayout.widget.ConstraintLayout>

Если приниципиальна скорость сборки xml когда в нём два элемента можете использовать такой код(если сможете уместить вопросы с 200dp высотой)

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GameActivity">

    <LinearLayout
        android:id="@+id/questionLayout"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginStart="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="10dp"
        android:background="#77B4CE"
        android:gravity="center|center_horizontal|top"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:id="@+id/questionTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/dummy_content"
            android:textSize="36sp" />

        <ProgressBar
            android:id="@+id/questionCountdownProgressBar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="25dp" />
    </LinearLayout>


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/answersView"
        android:layout_below="@id/questionLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="250dp"
        android:layout_marginEnd="0dp"
        android:layout_marginBottom="0dp"
        android:padding="0dp"
        android:scrollbars="horizontal" />
</FrameLayout>

Или попробуйте просто задать для вашего RecyclerView такой же marginTop как и для TextView

1
  • 1
    ConstraintLayout был разработан специально для одноуровневой верстки (чтобы не было необходимости размещать одни контейнеры внутри других, что очень печально сказывается на производительности), для этого у него есть множество инструментов и возможностей. а потом видишь подобную верстку и понимаешь, что андроид никогда не избавится от репутации тормознутого и лагучего.
    – pavlofff
    16 янв 2020 в 11:04
0

В item.xml android:layout_height задать свойство wrap_content

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    ....

</LinearLayout>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.