Пользовательский вид с viewpager внутри диалога не работает - PullRequest
0 голосов
/ 24 мая 2019

Я пытаюсь раздуть пользовательское диалоговое окно с пользовательским представлением, включающим ViewPager.Я получаю сообщение об ошибке типа «Не найдено представление для фрагмента внутри ViewPager».ViewPager, кажется, вызывает некоторые проблемы здесь, и я не мог найти никаких ответов на этот конкретный случай.

пытался использовать alertdialog.builder для построения диалога, но ошибка сохраняется.Попытка получить правильный контекст все еще не может решить эту ошибку.

Ссылку на репозиторий можно найти здесь - https://github.com/Alfurquan/CustomCalendarView

Это onCreate моей основной деятельности

 setContentView(R.layout.activity_month_picker);
        btn = findViewById(R.id.clickToOpn);
        customMonthPicker = findViewById(R.id.customMonthPicker1);
//        customMonthPicker.setOnMonthSelectedListener(new OnMonthSelectedListener() {
//            @Override
//            public void onSelectedMonth(int month) {
//                Log.d("msgMonth", String.valueOf(month));
//            }
//        });
//
//        customMonthPicker.setOnYearSelectedListener(new OnYearSelectedListener() {
//            @Override
//            public void onYearSelected(int year) {
//                Log.d("msgYear", String.valueOf(year));
//            }
//        });

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CustomMonthAndYearPickerDialog dialog = new CustomMonthAndYearPickerDialog(MonthPickerActivity.this);
                dialog.setOnMonthSelectedListener(new OnMonthSelectedListener() {
                    @Override
                    public void onSelectedMonth(int month) {
                        Log.d("msgMonth", String.valueOf(month));
                    }
                });

                dialog.setOnYearSelectedListener(new OnYearSelectedListener() {
                    @Override
                    public void onYearSelected(int year) {
                        Log.d("msgYear", String.valueOf(year));

                    }
                });
                dialog.show();
            }
        });

Это код настраиваемого диалогового окна

public CustomMonthAndYearPickerDialog(@NonNull Context context) {
        super(context);
        setContentView(R.layout.custom_month_dialog);
        mContext = context;
        initialize();
        setClickListeners();
    }



    public CustomMonthAndYearPickerDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    protected CustomMonthAndYearPickerDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }
    private void initialize() {
        customMonthPicker = findViewById(R.id.customMonthPicker1);
        btnDone = findViewById(R.id.btnDone1);
        btnCancel = findViewById(R.id.btnCancel1);
    }

Это код настраиваемого представления

 Activity activity = getActivityFromContext(getContext());
        yearPagerAdapter = new YearPagerAdapter(((AppCompatActivity)activity).getSupportFragmentManager(),context,fragList);
        viewPager.setAdapter(yearPagerAdapter);


 @Nullable
    public Activity getActivityFromContext(@NonNull Context context){
        while (context instanceof ContextWrapper) {
            if (context instanceof Activity) return (Activity) context;
            context = ((ContextWrapper)context).getBaseContext();
        }
        return null; //we failed miserably
    }

Это адаптер видового пейджера

public class YearPagerAdapter extends FragmentPagerAdapter {

    private Context context;
    YearFragment[] fragList;
    private CalendarManager calendarManager;

    public YearPagerAdapter(FragmentManager fm,Context context,YearFragment[] fragList) {
        super(fm);
        this.context = context;
        this.fragList = fragList;
        calendarManager = new CalendarManager(context);
    }

    @Override
    public Fragment getItem(int position) {
        return fragList[position];
    }

    @Override
    public int getCount() {
        return 3;
    }

    public void setYears(Calendar currentYear){

        Calendar prevYear = Calendar.getInstance();
        prevYear.setTime(currentYear.getTime());
        prevYear.add(Calendar.MONTH,-12);
        int prev = prevYear.get(Calendar.YEAR);

        Calendar nextYear = Calendar.getInstance();
        nextYear.setTime(currentYear.getTime());
        nextYear.add(Calendar.MONTH, 12);
        int next = nextYear.get(Calendar.YEAR);
        int cur = currentYear.get(Calendar.YEAR);

        ArrayList<Integer> prevYears,currentYears,nextYears;
        prevYears = calendarManager.getYearList(prevYear);
        nextYears = calendarManager.getYearList(nextYear);
        currentYears = calendarManager.getYearList(currentYear);

        fragList[0].updateUI(prevYears);
        fragList[1].updateUI(currentYears);
        fragList[2].updateUI(nextYears);

    }
}

Этофрагмент

package com.example.customcalendar.fragments;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.example.customcalendar.R;
import com.example.customcalendar.adapter.YearGridAdapter;
import com.example.customcalendar.interfaces.OnYearSelectedListener;

import java.util.ArrayList;
import java.util.Calendar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class YearFragment extends Fragment {

    private ArrayList<Integer> yearList;
    private View view;
    private GridView yearGrid;
    int currentYear;
    public static int selectedYear;
    private YearGridAdapter yearGridAdapter;
    public static OnYearSelectedListener onYearSelectedListener;
    public YearFragment() {

    }

    @SuppressLint("ValidFragment")
    public YearFragment(ArrayList<Integer> yearList) {
        this.yearList = yearList;
    }

    public static YearFragment newInstance(ArrayList<Integer> yearList){
        return new YearFragment(yearList);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.year_view,container,false);
        initializeVariables();
        setUpYearGridAdapter();
        setUpYearGridClicks();
        return view;
    }

    private void initializeVariables() {
        yearGrid = view.findViewById(R.id.yearGrid);
        Calendar calendar = Calendar.getInstance();
        currentYear = calendar.get(Calendar.YEAR);
        selectedYear = currentYear;
    }

    private void setUpYearGridAdapter() {
        yearGridAdapter = new YearGridAdapter(view.getContext(),yearList,currentYear,selectedYear);
        yearGrid.setAdapter(yearGridAdapter);
    }

    private void setUpYearGridClicks() {
        yearGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                int year = yearGridAdapter.getItem(position);
                selectedYear = year;
                onYearSelectedListener.onYearSelected(selectedYear);
                setUpYearGridAdapter();
            }
        });
    }

    public void updateUI(ArrayList<Integer> yearList){
        this.yearList = yearList;
        setUpYearGridAdapter();
    }


}

это xml диалога

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

    <LinearLayout
    android:id="@+id/header"
    android:gravity="center"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="100sp">

    <TextView
    android:id="@+id/monthName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="April"
    android:padding="10sp"
    android:textSize="24sp"
    android:textColor="#000" />

    <TextView
    android:id="@+id/yearName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="2019"
    android:padding="10sp"
    android:textStyle="bold"
    android:textSize="24sp"
    android:textColor="#000" />

    </LinearLayout>

    <View
    android:layout_width="match_parent"
    android:layout_height="2sp"
    android:background="@color/grey"/>
    </LinearLayout>

    <com.example.customcalendar.views.CustomMonthPicker
        android:id="@+id/currentMonthPicker"
        android:layout_width="match_parent"
        android:layout_height="200sp"/>

    <LinearLayout
    android:orientation="horizontal"
    android:weightSum="1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
    android:id="@+id/btnCancel1"
    android:layout_width="0sp"
    android:layout_height="wrap_content"
    android:text="Cancel"
    android:layout_weight="0.5"/>
    <Button
    android:id="@+id/btnDone1"
    android:layout_width="0sp"
    android:layout_height="wrap_content"
    android:text="Done"
    android:layout_weight="0.5"/>
    </LinearLayout>

</LinearLayout>

и это сообщение об ошибке, которое я получаю:

Error message - "Process: com.example.customcalendar, PID: 17596
    java.lang.IllegalArgumentException: No view found for id 0x7f0700ab (com.example.customcalendar:id/yearPager) for fragment YearFragment{20a1ebd5 #0 id=0x7f0700ab android:switcher:2131165355:1}"
...