Я работаю над приложением Android, в котором есть три окна просмотра.Первый и второй виджеры содержат список переработчиков.
Первый класс Viewpager содержит имя клиента, и я отправил Client name
в Invoices Class(3rd Viewpager)
.
Я реализовал тот же метод для отправки данных списка переработчиков в класс Invoices.Данные будут отображаться в третьем списке viewpager
Recycler, но когда я возвращаюсь назад и снова возвращаюсь к третьему viewpager
, предыдущий выбранный элемент автоматически загружается в класс счетов-фактур.
ЗдесьМоя основная деятельность, которая содержит все три окна просмотра ...
public class MainFragment extends AppCompatActivity {
DatabaseHelper databaseHelper;
ViewPager viewPager;
String fname;
String namebltp;
GetSetProductsDetail listProduct;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_fragment);
databaseHelper=new DatabaseHelper(this);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Dynamic ERPMini");
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Clients"));
tabLayout.addTab(tabLayout.newTab().setText("Products"));
tabLayout.addTab(tabLayout.newTab().setText("Invoices"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = findViewById(R.id.pager);
final PagerAdapter adapter = new PagersAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void initialize() {
viewPager = findViewById(R.id.pager);
}
@Override
public void onResume() {
super.onResume();
viewPager = findViewById(R.id.pager);
}
public void fromThirdToSecond(int position) {
initialize();
viewPager.setCurrentItem(position);
}
public void selectTab(int position, String fname) {
initialize();
this.fname = fname;
viewPager.setCurrentItem(position);
}
public String getMyData() {
return fname;
}
public void selectTabProd(int position, GetSetProductsDetail listProduct) {
initialize();
this.listProduct = listProduct;
viewPager.setCurrentItem(position);
}
public String getMyProdData() {
return namebltp;
}
Вот мой второй класс просмотра (класс продукта);Он также имеет адаптер для него ..
public class Products extends Fragment {
RecyclerView recyclerViewProducts;
Button btnAllProducts;
ProductRecyclerAdapter productRecyclerAdapter;
List<GetSetProductsDetail> listproducts;
DatabaseHelper databaseHelper;
SearchView searchViewProd;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.products, container, false);
btnAllProducts=view.findViewById(R.id.searchallproducts);
recyclerViewProducts=view.findViewById(R.id.listprod);
searchViewProd=view.findViewById(R.id.searchproduct);
listproducts = new ArrayList<>();
productRecyclerAdapter = new ProductRecyclerAdapter(listproducts,recyclerViewProducts);
recyclerViewProducts.setItemAnimator(new DefaultItemAnimator());
recyclerViewProducts.setItemAnimator(new DefaultItemAnimator());
recyclerViewProducts.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerViewProducts.setHasFixedSize(true);
recyclerViewProducts.setAdapter(productRecyclerAdapter);
databaseHelper = new DatabaseHelper(getActivity());
searchViewProd.setOnSearchClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getAllProductsFromSqlite();
}
});
searchViewProd.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
SearchSQliteProduct(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
btnAllProducts.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getAllProductsFromSqlite();
}
});
return view;
}
@SuppressLint("StaticFieldLeak")
private void SearchSQliteProduct(final String query) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
listproducts.clear();
listproducts.addAll(databaseHelper.SearchprodData(query));
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
productRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
@SuppressLint("StaticFieldLeak")
private void getAllProductsFromSqlite() {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
listproducts.clear();
listproducts.addAll(databaseHelper.getAllProductsData());
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
productRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
}
Это мой адаптер вышестоящего класса (класса продукта)
public class ProductRecyclerAdapter extends RecyclerView.Adapter<ProductRecyclerAdapter.ClientViewHolder> {
private List<GetSetProductsDetail> listProduct;
Context mContext;
RecyclerView mRecyclerView;
View itemView;
public ProductRecyclerAdapter(List<GetSetProductsDetail> listProduct, RecyclerView recyclerView) {
this.listProduct = listProduct;
mRecyclerView = recyclerView;
}
@Override
public ClientViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mContext = parent.getContext();
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.items_products_table, parent, false);
return new ClientViewHolder(itemView);
}
public class ClientViewHolder extends RecyclerView.ViewHolder {
public TextView lblPName;
public TextView lblTrade;
public TextView lblRetail;
public TextView lblSubCategary;
public TextView lblCompany;
RelativeLayout layout;
public ClientViewHolder(View view) {
super(view);
lblPName = view.findViewById(R.id.lblPName);
lblTrade = view.findViewById(R.id.lblTrade);
lblRetail = view.findViewById(R.id.lblRetail);
lblSubCategary = view.findViewById(R.id.lblSubCategary);
lblCompany = view.findViewById(R.id.lblCompany);
layout = view.findViewById(R.id.listprod);
}
}
@Override
public void onBindViewHolder(ClientViewHolder holder, final int position) {
holder.lblPName.setText(listProduct.get(position).getNAME());
holder.lblTrade.setText(listProduct.get(position).getTRADE());
holder.lblRetail.setText(listProduct.get(position).getRETAIL());
holder.lblSubCategary.setText(listProduct.get(position).getSUBCATAGARY());
holder.lblCompany.setText(listProduct.get(position).getCOMPANY());
holder.layout.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
displayingAlertDialog(position);
return false;
}
});
}
@Override
public int getItemCount() {
Log.v(ProductRecyclerAdapter.class.getSimpleName(), "" + listProduct.size());
return listProduct.size();
}
private void displayingAlertDialog(final int position) {
final GetSetClientRec getSetClientsDetail= new GetSetClientRec();
AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext());
builder.setTitle("Choose Option");
builder.setMessage("Add Product Invoice?");
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
gotoInvoiceClass(listProduct.get(position));
dialog.cancel();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
}
private void gotoInvoiceClass(GetSetProductsDetail listProduct) {
MainFragment main = (MainFragment) mContext;
Toast.makeText(main, "Product Added " + listProduct, Toast.LENGTH_SHORT).show();
main.selectTabProd(2, listProduct);
}
}
Вот класс My Invoices (третий Viewpager; класс, в который данные загружаются автоматически)
public class Invoices extends Fragment {
TextView EdtName;
EditText EditCurrDate;
EditText EdtCurrDate2;
TextView EdtNameProdInvoiuce;
RecyclerView recyclerViewProdInvoice;
InvoicesRecyclerAdapter invoicesRecyclerAdapter;
List<GetSetProductsDetail> listproductsInvoices;
DatabaseHelper databaseHelper;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.invoice, container, false);
recyclerViewProdInvoice=view.findViewById(R.id.recyclerviewinvoicesprod);
databaseHelper = new DatabaseHelper(getActivity());
listproductsInvoices = new ArrayList<>();
String date_n = new SimpleDateFormat("MMM / dd / yyyy", Locale.getDefault()).format(new Date());
EditCurrDate = view.findViewById(R.id.currdate);
EdtCurrDate2 = view.findViewById(R.id.currdate1);
EdtName = view.findViewById(R.id.txtclientname);
EdtNameProdInvoiuce = view.findViewById(R.id.edtprodinvoice);
MainFragment activity = (MainFragment) getActivity();
String name = activity.getMyData();
EdtName.setText(name);
MainFragment activityprodinvoice = (MainFragment) getActivity();
String namebltp = activityprodinvoice.getMyProdData();
EdtNameProdInvoiuce.setText(namebltp);
EdtName.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Choose Option");
builder.setMessage("Are You Sure You Want To Add New Client?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MainFragment main = (MainFragment) getActivity();
main.fromThirdToSecond(0);
dialog.cancel();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
return false;
}
});
EditCurrDate.setText(date_n);
EdtCurrDate2.setText(date_n);
EditCurrDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mcurrentDate = Calendar.getInstance();
int year = mcurrentDate.get(Calendar.YEAR);
int month = mcurrentDate.get(Calendar.MONTH);
int day = mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedYear, int selectedMonth, int selectedDay) {
// TODO Auto-generated method stub
Log.e("Date Selected", "Month: " + selectedMonth + " Day: " + selectedDay + " Year: " + selectedYear);
EditCurrDate.setText((selectedMonth + 1) + "/" + selectedDay + "/" + selectedYear);
}
}, year, month, day);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
EdtCurrDate2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mcurrentDate = Calendar.getInstance();
int year1 = mcurrentDate.get(Calendar.YEAR);
int month1 = mcurrentDate.get(Calendar.MONTH);
int day1 = mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedYear, int selectedMonth, int selectedDay) {
// TODO Auto-generated method stub
Log.e("Date Selected", "Month: " + selectedMonth + " Day: " + selectedDay + " Year: " + selectedYear);
EdtCurrDate2.setText((selectedMonth + 1) + "/" + selectedDay + "/" + selectedYear);
}
}, year1, month1, day1);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
return view;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isResumed() && isVisibleToUser) {
MainFragment activity = (MainFragment) getActivity();
String namebltp = activity.getMyProdData();
EdtNameProdInvoiuce.setText(namebltp);
GetSetProductsDetail product = activity.listProduct;
listproductsInvoices.add(product);
invoicesRecyclerAdapter = new InvoicesRecyclerAdapter(listproductsInvoices,recyclerViewProdInvoice);
recyclerViewProdInvoice.setItemAnimator(new DefaultItemAnimator());
recyclerViewProdInvoice.setItemAnimator(new DefaultItemAnimator());
recyclerViewProdInvoice.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerViewProdInvoice.setHasFixedSize(true);
recyclerViewProdInvoice.setAdapter(invoicesRecyclerAdapter);
}
}
}
Текущая ситуация загрузки данных в класс Invoices
..
Выберите элемент из второго класса виджета. Загружается в третий класс.Сдвиньте назад и снова откройте третий класс, данные снова загрузятся в третий viewpager Class
Это отображается на тосте, когда я выбираю элемент из класса Product и перехожу в третий класс VIewpager, Invoice
Изображение тоста
Я добавил тост Нравится
private void gotoInvoiceClass(GetSetProductsDetail listProduct) {
MainFragment main = (MainFragment) mContext;
Toast.makeText(main, "Product Added " + listProduct, Toast.LENGTH_SHORT).show();
main.selectTabProd(2, listProduct);
}