如何使用 tablayout 和片段管理 java 文件

How to manage java file with tablayout and fragments

我正在使用 firestore 开发一个简单的应用程序。在这种情况下,为了更好的功能和客户友好性,我将带有片段的 tablayout 概念输入到我的应用程序中。当我使用时,出现了一些错误。我试过了,但我无法修复它。所以我想要的是,影响那种错误的情况是什么?如果你熟悉我说的,请帮助我。

this is the java file that i want to code in one fragment. 
package com.example.work_home;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;

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

import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import static android.content.ContentValues.TAG;
import static com.example.work_home.R.id.txt_select_leave;

public class Apply extends Fragment {
    private AutoCompleteTextView SelectLeave, LeaveType;
    TextInputEditText FromDate, ToDate;
    EditText Reason;
    private DatePickerDialog dataPickerDialog_from;
    private DatePickerDialog dataPickerDialog_to;
    Button BtnSubmit;
    BottomNavigationView BtnBottom;
    View v;
    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseUser FUser = auth.getCurrentUser();
    public String UserId = FUser.getUid();

    private FirebaseFirestore db = FirebaseFirestore.getInstance();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        v = inflater.inflate(R.layout.fragment_apply, container, false);
        return v;
        SelectLeave = v.findViewById(txt_select_leave);
        LeaveType = v.findViewById(R.id.txt_leave_type);
        FromDate = v.findViewById(R.id.txt_from_user);
        ToDate = v.findViewById(R.id.txt_to_user);
        Reason = v.findViewById(R.id.txt_reason_user);
        BtnSubmit = v.findViewById(R.id.btn_submit);
        BtnBottom = v.findViewById(R.id.btn_bottom_navigation_leave);


        BtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String selectLeave = SelectLeave.getText().toString();
                String leaveType = LeaveType.getText().toString();
                String fromDate = FromDate.getText().toString();
                String toDate = ToDate.getText().toString();
                String reason = Reason.getText().toString();

                DocumentReference documentReference = db.collection("users").document(UserId);
                DocumentReference documentReference_two = documentReference.collection("ApplyLeave").document();

                Map<String, Object> LeaveData = new HashMap<>();
                LeaveData.put("u_select_leave", selectLeave);
                LeaveData.put("u_leave-type", leaveType);
                LeaveData.put("u_from_date", fromDate);
                LeaveData.put("u_to_date", toDate);
                LeaveData.put("u_reason", reason);

                documentReference_two.set(LeaveData);

            }
        });


        FromDate.setText(getTodayDate());
        ToDate.setText(getTodayDate());

        initDatePicker_from();
        initDatePicker_to();

        String[] Select_Leave = new String[]{
                "Casual Leave", "Sick Leave", "Annual Leave ", "Maternity Leave", "Paternity Leave"
                , "Compensatory Off", "Other"};

        ArrayAdapter adapter = new ArrayAdapter<>(
                Apply.this, R.layout.dropdown_item, Select_Leave
        );
        SelectLeave.setAdapter(adapter);

        String[] Leave_Type = new String[]{
                "Full Day", "Half Day", "Other"};

        ArrayAdapter<String> adapter_one = new ArrayAdapter<>(
                Apply.this, R.layout.dropdown_item, Leave_Type
        );
        LeaveType.setAdapter(adapter_one);

        /*BtnBottom.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.logout:
                        Intent logout = new Intent(Apply.this, Login.class);
                        startActivity(logout);
                        overridePendingTransition(0, 0);
                        return true;
                    case R.id.home:
                        Intent home = new Intent(Apply_leave.this, Home.class);
                        startActivity(home);
                        overridePendingTransition(0, 0);
                        return true;
                    case R.id.user:
                        Intent user = new Intent(Apply_leave.this, UserProfile.class);
                        startActivity(user);
                        overridePendingTransition(0, 0);
                        return true;
                    /*case R.id.alerts:
                        Intent alerts = new Intent(Apply_leave.this, Notifications.class);
                        startActivity(alerts);
                        overridePendingTransition(0, 0);
                        return true;

                }
                return false;
            }
        });*/


    }

    private String getTodayDate() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        month = month + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        return makeDataString(day, month, year);


    }


    private void initDatePicker_from() {
        DatePickerDialog.OnDateSetListener dataSetListener_from = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                month = month + 1;
                String date_from = makeDataString(dayOfMonth, month, year);
                FromDate.setText(date_from);
            }
        };
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        int style = AlertDialog.THEME_HOLO_LIGHT;
        dataPickerDialog_from = new DatePickerDialog(this, style, dataSetListener_from, year, month, day);
        dataPickerDialog_from.getDatePicker().setMaxDate(System.currentTimeMillis());
    }

    private void initDatePicker_to() {
        DatePickerDialog.OnDateSetListener dataSetListener_to = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                month = month + 1;
                String date_to = makeDataString(dayOfMonth, month, year);
                ToDate.setText(date_to);
            }
        };
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        int style = AlertDialog.THEME_HOLO_LIGHT;
        dataPickerDialog_to = new DatePickerDialog(this, style, dataSetListener_to, year, month, day);
        dataPickerDialog_to.getDatePicker().setMaxDate(System.currentTimeMillis());
    }

    private String makeDataString(int dayOfMonth, int month, int year) {
        return getMonthFormat(month) + " " + dayOfMonth + " " + year;
    }

    private String getMonthFormat(int month) {
        if (month == 1)
            return "JAN";
        if (month == 2)
            return "FEB";
        if (month == 3)
            return "MAR";
        if (month == 4)
            return "APR";
        if (month == 5)
            return "MAY";
        if (month == 6)
            return "JUN";
        if (month == 7)
            return "JUL";
        if (month == 8)
            return "AUG";
        if (month == 9)
            return "SEP";
        if (month == 10)
            return "OCT";
        if (month == 11)
            return "NOV";
        if (month == 12)
            return "DEC";

        return "JAN";

    }

    public void openDatePicker_from(View view) {
        dataPickerDialog_from.show();

    }

    public void openDatePicker_to(View view) {
        dataPickerDialog_to.show();


    }
}

*****这是我的 tablayout(main.xml) 文件的布局[在此处输入图片描述][1]

******* 这是 apply.xml 文件的布局******** [在此处输入图片描述][2]

这是我的适配器文件 *****

package com.example.work_home;

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

import java.util.ArrayList;

public class VPAdapter extends FragmentPagerAdapter {

    private final ArrayList<Fragment> fragmentArrayList = new ArrayList<>();
    private final ArrayList<String> fragmentTitle = new ArrayList<>();


    public VPAdapter(@NonNull FragmentManager fm, int behavior) {
        super(fm, behavior);
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return fragmentArrayList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentArrayList.size();
    }
    public void addFragment(Fragment fragment, String title){
        fragmentArrayList.add(fragment);
        fragmentTitle.add(title);

    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {

        return fragmentTitle.get(position);
    }
}

So if You are familiar with these kind of problem please help me..

*代码错误

error: cannot infer type arguments for ArrayAdapter<>
        ArrayAdapter<String> adapter_one = new ArrayAdapter<>(
                                           ^
error: incompatible types: Apply cannot be converted to Context
        dataPickerDialog_from = new DatePickerDialog(this, style, dataSetListener_from, year, month, day);
                                                     ^
error: unreachable statement
        SelectLeave = v.findViewById(txt_select_leave);
        ^
******************errors****************************
[enter image description here][3] 
[enter image description here][4]


  [1]: https://i.stack.imgur.com/hDZcQ.png
  [2]: https://i.stack.imgur.com/sAVCB.png
  [3]: https://i.stack.imgur.com/vbChu.png
  [4]: https://i.stack.imgur.com/uuDg3.png

这些是 Java 编译错误。

error: cannot infer type arguments for ArrayAdapter<>
        ArrayAdapter<String> adapter_one = new ArrayAdapter<>(
              Apply.this, R.layout.dropdown_item, Select_Leave
        );

所以问题是 ArrayAdapter 的所有构造函数都需要 Context 作为第一个参数。但是你给了它一个Apply。并且 Apply 已被声明为 Fragment ... 而 Fragment 不是 Context.

error: incompatible types: Apply cannot be converted to Context
        dataPickerDialog_from = new DatePickerDialog(
             this, style, dataSetListener_from, year, month, day);

这几乎是同一个问题。 DatePickerDialog 构造函数都需要一个 Context 作为第一个参数,但是 this 是一个 Apply 而不是 Context.

我对此不是 100% 确定,但我认为您应该在 Apply / Fragment 实例上调用 getContext() 并将结果传递给这两个构造函数。 ..


请注意,您可以(并且应该)查找并阅读 Android 库 类 的 javadoc 以了解如何使用它们。例如,Fragment 的 javadoc 告诉您 Fragment 不是 Context ... 但它确实有一个 getContext() 方法。