Tab item title in tablayout displaying not well arranged - java

I am working on an existing project where tablayout is integrated but the tab items title are not displaying well arranged. Below is screenshot of what it looks like and also a screenshot of how i want it to look like
This is actually how i want the tab item title displaying
This is my xml file code snippet:
<?xml version="1.0" encoding="utf-8"?>
<layout 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"
tools:context=".salesinvoice.fragments.SalesInvoiceInstanceFragment">
<data>
<variable
name="salesRecord"
type="com.mainsoftdc.costoma.salesinvoice.entities.SalesRecord" />
<variable
name="eventHandler"
type="com.mainsoftdc.costoma.salesinvoice.eventhandlers.SalesInvoiceInstanceEventHandler" />
<import type="com.mainsoftdc.costoma.shared.utils.DecimalFormatter" />
<import type="com.mainsoftdc.costoma.shared.utils.MoneyFormatter" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/sales_instance_top_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorGreyLight"
android:orientation="horizontal"
android:paddingLeft="#dimen/padding_xs"
android:paddingRight="#dimen/padding_xs"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="#+id/btn_edit_sale_instance_customer_name"
style="#style/BtnTextPrimarySmNoPadding"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="#{() -> eventHandler.editCustomerName()}"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_edit_customer_name"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/text_12sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btn_close_sale_instance"
style="#style/BtnTextPrimarySmNoPadding"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="#{() -> eventHandler.closeSaleInstance()}"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_close_invoice"
android:textColor="#color/colorRed"
android:textSize="#dimen/text_12sp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/sales_product_list_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingStart="#dimen/padding_xs"
android:paddingTop="#dimen/padding_xxs"
android:paddingEnd="#dimen/padding_xs"
android:paddingBottom="#dimen/no_padding"
app:layout_constraintTop_toBottomOf="#id/sales_instance_top_layout">
<TextView
android:id="#+id/sales_instance_items"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_all_items"
android:textColor="#android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="#+id/btn_add_item_to_sales"
style="#style/BtnSecondarySmOutlined"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:gravity="center"
android:minWidth="0dp"
android:minHeight="0dp"
android:onClick="#{() -> eventHandler.addItemToSalesBook()}"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_add_item"
android:textSize="#dimen/text_10sp"
app:icon="#drawable/ic_add_circle_black_24dp"
app:iconSize="14dp"
app:iconTint="#color/colorAccent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<LinearLayout
android:id="#+id/sales_instance_product_list"
style="#style/ListPage"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toTopOf="#id/sales_instance_buttons"
app:layout_constraintTop_toBottomOf="#id/sales_product_list_header"
>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/sales_instance_product_list_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:layout_marginBottom="#dimen/margin_md"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</LinearLayout>
<LinearLayout
android:id="#+id/sales_instance_sales_summary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorGreyLight"
android:orientation="horizontal"
android:paddingLeft="#dimen/padding_sm"
android:paddingRight="#dimen/padding_sm"
android:paddingTop="#dimen/padding_xs"
android:paddingBottom="#dimen/padding_xs"
app:layout_constraintBottom_toTopOf="#id/sales_instance_buttons">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="2"
android:orientation="vertical">
<TextView
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sales_instance_total_volume"
android:textColor="#color/colorBlack" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{DecimalFormatter.format(salesRecord.totalProductsSold)}"
android:textColor="#color/colorPrimaryDark"
android:textSize="#dimen/text_16sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="3"
android:orientation="vertical"
android:textColor="#color/colorBlack">
<TextView
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:text="#string/sale_instance_total_value"
android:textColor="#color/colorBlack" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:text="#{MoneyFormatter.format(salesRecord.totalSellingPrice)}"
android:textColor="#color/colorPrimaryDark"
android:textSize="#dimen/text_16sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/sales_instance_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:orientation="horizontal"
android:paddingLeft="#dimen/padding_xs"
android:paddingTop="#dimen/no_padding"
android:paddingRight="#dimen/padding_xs"
android:paddingBottom="#dimen/no_padding"
app:layout_constraintBottom_toBottomOf="parent">
<com.google.android.material.button.MaterialButton
android:id="#+id/sale_instance_quote_btn"
style="#style/BtnTextPrimarySm"
android:layout_width="0dp"
android:layout_height="38dp"
android:layout_gravity="start"
android:layout_margin="0dp"
android:layout_marginLeft="#dimen/margin_md"
android:layout_weight="1"
android:background="#drawable/xml_drawable_rectangle_border"
android:onClick="#{() ->eventHandler.saveAsQuote()}"
android:text="#string/sales_instance_quote_btn"
android:textAlignment="viewStart"
android:textColor="#android:color/white"
android:textSize="#dimen/text_14sp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/sale_instance_checkout_print_btn"
style="#style/BtnTextPrimarySm"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="0dp"
android:layout_marginRight="#dimen/margin_md"
android:layout_weight="2"
android:background="#drawable/xml_drawable_rectangle_border"
android:onClick="#{() ->eventHandler.captureAmountPaidAndCompleteSales()}"
android:text="#string/sale_instance_proceed_to_checkout"
android:textAlignment="viewEnd"
android:textColor="#android:color/white"
android:textSize="#dimen/text_14sp" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
This is my Adapter Code snippet:
public class SalesInvoicePagerAdapter extends FragmentStatePagerAdapter {
private SalesInvoiceViewModel salesInvoiceViewModel;
private List<SalesRecord> activeSalesRecords = new ArrayList<>();
#SuppressLint("UseSparseArrays")
public SalesInvoicePagerAdapter(final Fragment ownerFragment, SalesInvoiceViewModel salesViewModel) {
super(ownerFragment.getChildFragmentManager());
salesInvoiceViewModel = salesViewModel;
salesInvoiceViewModel.getActiveSalesRecords().observe(ownerFragment, new Observer<List<SalesRecord>>() {
#Override
public void onChanged(#Nullable List<SalesRecord> salesRecords) {
activeSalesRecords = salesRecords;
notifyDataSetChanged();
}
});
salesInvoiceViewModel.newSaleAlert.observe(ownerFragment, new Observer<SalesRecord>() {
#Override
public void onChanged(#Nullable SalesRecord salesRecord) {
Log.i("New Alert", String.valueOf(activeSalesRecords.size()));
activeSalesRecords.add(salesRecord);
notifyDataSetChanged();
}
});
salesInvoiceViewModel.saleClosedAlert.observe(ownerFragment, new Observer<Integer>() {
#Override
public void onChanged(Integer instancePosition) {
if(activeSalesRecords.size() > 0) {
activeSalesRecords.remove((int) instancePosition);
notifyDataSetChanged();
}
}
});
salesInvoiceViewModel.saleUpdatedAlert.observe(ownerFragment, new Observer<Pair<Integer, SalesRecord>>() {
#Override
public void onChanged(#Nullable Pair<Integer, SalesRecord> updatedSalesRecordPair) {
if(updatedSalesRecordPair != null) {
activeSalesRecords.remove((int) updatedSalesRecordPair.first);
activeSalesRecords.add(updatedSalesRecordPair.first, updatedSalesRecordPair.second);
notifyDataSetChanged();
}
}
});
}
#Override
public Fragment getItem(int i) {
Log.i("Set Current", String.valueOf(activeSalesRecords.size()));
if (activeSalesRecords.size() > 0) {
Fragment fragment = new SalesInvoiceInstanceFragment();
Bundle bundle = new Bundle();
bundle.putString(IntentExtras.SALES_INSTANCE_GUID, activeSalesRecords.get(i).getGuid());
bundle.putInt(IntentExtras.SALES_INSTANCE_FRAGMENT_POSITION, i);
fragment.setArguments(bundle);
return fragment;
}
return null;
}
#Override
public int getCount() {
return activeSalesRecords.size();
}
// #Nullable
#Override
public CharSequence getPageTitle(int position) {
Log.i("NAME: ", activeSalesRecords.get(position).getCustomerName());
Log.i("Page Title: ", activeSalesRecords.get(position).getCustomerName());
return activeSalesRecords.get(position).getCustomerName();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
This is my Fragment file code snippet:
public class SalesInvoiceFragment extends BaseFragment implements View.OnClickListener {
private static final String LOG_TAG = SalesInvoiceFragment.class.getName();
private FragmentSalesInvoiceBinding dataBinding;
private SalesInvoicePagerAdapter salesInvoicePagerAdapter;
private SalesInvoiceViewModel salesInvoiceViewModel;
private Activity parentActivity;
private AuthorityVerification authorityVerification;
#Inject
public SharedPreferencesRepository sharedPreferencesRepository;
#Inject
public SubscriptionPlanService subscriptionPlanService;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("Tab", "CHECKING...");
daggerComponent.inject(this);
dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_sales_invoice, container, false);
salesInvoiceViewModel = ViewModelProviders.of(this, new CostomaViewModelFactory((CostomaApplication) getActivity().getApplication())).get(SalesInvoiceViewModel.class);
authorityVerification = new AuthorityVerification(requireActivity());
parentActivity = getActivity();
return dataBinding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dataBinding.salesInvoiceFragmentTabLayout.setupWithViewPager(dataBinding.salesInvoiceFragmentViewPager);
salesInvoicePagerAdapter = new SalesInvoicePagerAdapter(this, salesInvoiceViewModel);
dataBinding.salesInvoiceFragmentViewPager.setAdapter(salesInvoicePagerAdapter);
Log.i("ONCRE", "START");
// for(int i=0; i < salesInvoicePagerAdapter.getCount(); i++) {
// Log.i("DeTitle", "PAGE TITLE");
// Log.i("DeTitle: ", salesInvoicePagerAdapter.getPageTitle(i).toString());
// //dataBinding.salesInvoiceFragmentTabLayout.addTab(dataBinding.salesInvoiceFragmentTabLayout.newTab().setText(salesInvoicePagerAdapter.getPageTitle(i)));
// dataBinding.salesInvoiceFragmentTabLayout.getTabAt(i).setText(salesInvoicePagerAdapter.getPageTitle(i));
// }
if (!subscriptionPlanService.hasActiveSubscription()) {
dataBinding.startSaleBtn.setVisibility(View.GONE);
dataBinding.noActiveSubLabel.setVisibility(View.VISIBLE);
} else {
dataBinding.startSaleBtn.setVisibility(View.VISIBLE);
dataBinding.noActiveSubLabel.setVisibility(View.GONE);
dataBinding.startSaleBtn.setOnClickListener(this);
}
setDisplayedViewsForActiveSalesCount(0);
salesInvoiceViewModel.salesCountChangedAlert.observe(this, new Observer<Integer>() {
#Override
public void onChanged(#NonNull Integer totalActiveSales) {
Log.i("Set Current", String.valueOf(salesInvoicePagerAdapter.getCount()));
if (totalActiveSales > 0) {
// dataBinding.salesInvoiceFragmentTabLayout.addTab(dataBinding.salesInvoiceFragmentTabLayout.newTab().setText(salesInvoicePagerAdapter.getPageTitle(totalActiveSales - 1)));
for(int i=0; i < salesInvoicePagerAdapter.getCount(); i++) {
// Log.i("DeTitle", "PAGE TITLE");
// Log.i("DeTitle: ", salesInvoicePagerAdapter.getPageTitle(i).toString());
//dataBinding.salesInvoiceFragmentTabLayout.addTab(dataBinding.salesInvoiceFragmentTabLayout.newTab().setText(salesInvoicePagerAdapter.getPageTitle(i)));
dataBinding.salesInvoiceFragmentTabLayout.getTabAt(i).setText(salesInvoicePagerAdapter.getPageTitle(i));
}
dataBinding.salesInvoiceFragmentViewPager.setCurrentItem(totalActiveSales - 1);
// if (dataBinding.salesInvoiceFragmentTabLayout.getTabCount() == 2) {
// dataBinding.salesInvoiceFragmentTabLayout.setTabMode(TabLayout.MODE_FIXED);
// } else {
// dataBinding.salesInvoiceFragmentTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
// }
}
setDisplayedViewsForActiveSalesCount(totalActiveSales);
setActivityTitle(totalActiveSales);
}
});
}
private void setDisplayedViewsForActiveSalesCount(int activeSalesCount) {
if (activeSalesCount > 0) {
dataBinding.salesInvoiceFragmentViewPager.setVisibility(View.VISIBLE);
dataBinding.salesInvoiceFragmentBlankSales.setVisibility(View.GONE);
} else {
dataBinding.salesInvoiceFragmentViewPager.setVisibility(View.GONE);
dataBinding.salesInvoiceFragmentBlankSales.setVisibility(View.VISIBLE);
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
salesInvoiceViewModel.commitActiveSales();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_sale_btn:
showAddSaleDialog();
break;
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.sales_invoice_menu, menu);
boolean currentPdfGenerationValue = sharedPreferencesRepository.getBooleanValue(SharedPreferenceKeys.GENERATE_PDF_FOR_INVOICE);
boolean currentMerchantReceiptValue = sharedPreferencesRepository.getBooleanValue(SharedPreferenceKeys.PRINT_MERCHANT_COPY_FOR_RECEIPT);
menu.findItem(R.id.menu_item_invoice_pdf_generation_setting).setChecked(currentPdfGenerationValue);
menu.findItem(R.id.menu_item_invoice_merchant_copy_receipt).setChecked(currentMerchantReceiptValue);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_item_create_sales_instance:
if (!subscriptionPlanService.hasActiveSubscription()) {
ToastUtils.showLongToast(requireActivity(), "You do not have an active subscription!");
return true;
}
showAddSaleDialog();
break;
case R.id.menu_item_invoice_pdf_generation_setting:
boolean generateInvoice = !item.isChecked();
item.setChecked(generateInvoice);
sharedPreferencesRepository.saveBooleanValue(SharedPreferenceKeys.GENERATE_PDF_FOR_INVOICE, generateInvoice);
break;
case R.id.menu_item_invoice_merchant_copy_receipt:
boolean printMerchantReceipt = !item.isChecked();
item.setChecked(printMerchantReceipt);
sharedPreferencesRepository.saveBooleanValue(SharedPreferenceKeys.PRINT_MERCHANT_COPY_FOR_RECEIPT, printMerchantReceipt);
}
return true;
}
private void showAddSaleDialog() {
NewSaleDialog dialog = new NewSaleDialog();
dialog.setSalesInvoiceViewModel(salesInvoiceViewModel);
dialog.show(getFragmentManager(), NewSaleDialog.FRAGMENT_TAG);
}
private void setActivityTitle(int totalSalesCount) {
if (parentActivity != null) {
if (totalSalesCount > 0) {
parentActivity.setTitle(getString(R.string.menu_item_sales_invoice) + " - " + String.valueOf(totalSalesCount));
} else {
parentActivity.setTitle(R.string.menu_item_sales_invoice);
}
}
parentActivity.getActionBar();
}
}
I have tried everything i can to make it display well but is not working. I will welcome any assistance as i need to get this resolved now.
Thanks in advance....

Related

Combine use of OnClickListener and OnLong Click Listener

Actually I created a pdf viewer and i jus want to create a longclicklistener to open my new activity and as u can see here
Screenshot
And there is already a click listener assigned with this button and i also want to combine longclicklistener so when i long click that button then automatically launch my second activity
public void actionButtonClick(View view) {
if (pageCount == 0) {
Toast.makeText(getApplicationContext(), getString(R.string.no_selected_pdf), Toast.LENGTH_LONG).show();
return;
}
final BottomSheetDialog dialog = new BottomSheetDialog(MainActivity.this);
dialog.setContentView(R.layout.bottom_sheet);
dialog.setCanceledOnTouchOutside(true);
NumberPicker numberPicker = (NumberPicker) dialog.findViewById(R.id.number_picker);
if (numberPicker != null) {
numberPicker.setMaxValue(pageCount);
numberPicker.setValue(pdfView.getCurrentPage() + 1);
numberPicker.setOnValueChangedListener((picker, oldVal, newVal) -> {
pdfView.jumpTo(newVal - 1, true);
});
}
dialog.show();
}
public void openButtonClick(View view) {
launchPicker();
}
private void startAnimation(int state) {
actionLayout.animate()
.translationY(state == 0 ? actionLayout.getHeight() : 0)
.alpha(state == 0 ? 0 : 1.0f)
.setDuration(300).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
menu.findItem(R.id.hide_or_show_button).setChecked(state != 1);
super.onAnimationEnd(animation);
}
});
}
private void hideOrShowActionButton() {
if (actionLayout.getAlpha() == 1.0)
startAnimation(0);
else
startAnimation(1);
}
private void showSnackBar(#NonNull String msg, boolean isError) {
Snackbar snackbar = Snackbar
.make(findViewById(R.id.main_layout), msg, Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(ContextCompat
.getColor(Objects.requireNonNull(getApplicationContext()),
isError ? R.color.err_color : R.color.main_color));
snackbar.setTextColor(ContextCompat
.getColor(Objects.requireNonNull(getApplicationContext()), R.color.white));
snackbar.show();
}
#Override
public void loadComplete(int nbPages) {
pageCount = nbPages;
warningLayout.setVisibility(View.GONE);
PdfDocument.Meta meta = pdfView.getDocumentMeta();
detailsMap.clear();
detailsMap.add(meta.getTitle());
detailsMap.add(meta.getAuthor());
detailsMap.add(meta.getSubject());
detailsMap.add(meta.getKeywords());
detailsMap.add(meta.getCreator());
detailsMap.add(meta.getProducer());
detailsMap.add(dateFormatter(meta.getCreationDate()));
detailsMap.add(dateFormatter(meta.getModDate()));
}
private String dateFormatter(String data) {
if (!data.isEmpty()) {
String date = data.substring(2);
String y = date.substring(0, 4);
String m = date.substring(4, 6);
String d = date.substring(6, 8);
return y + "/" + m + "/" + d;
} else {
return data;
}
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber.setText(String.valueOf(page + 1));
}
#Override
public void onPageError(int page, Throwable t) {
showSnackBar(getString(R.string.page_not_loaded) + page, true);
}
}
Xml File
This Is Xml File if needed
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
tools:context=".MainActivity">
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdf_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
app:layout_anchor="#+id/warning"
app:layout_anchorGravity="center">
<Button
android:id="#+id/button"
android:layout_width="42dp"
android:layout_height="11dp"
android:layout_below="#id/textView"
android:layout_alignParentBottom="true"
android:layout_marginBottom="518dp"
android:text="open activity 2" />
</com.github.barteksc.pdfviewer.PDFView>
<LinearLayout
android:id="#+id/warning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/no_selected_pdf"
android:textColor="#color/secondary_text_color"
android:textSize="16sp" />
<TextView
android:id="#+id/tv_open_pdf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="true"
android:focusable="true"
android:onClick="openButtonClick"
android:padding="10dp"
android:text="#string/click_to_select_pdf"
android:textColor="#color/main_color"
android:textSize="18sp" />
</LinearLayout>
<FrameLayout
android:id="#+id/action_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/action_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="20dp"
android:contentDescription="#string/action_btn_description"
android:onClick="actionButtonClick"
app:backgroundTint="#color/main_color"
app:borderWidth="0dp"
app:tint="#color/white" />
<TextView
android:id="#+id/tv_page_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:elevation="16dp"
android:text="x"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/white"
android:textSize="16sp" />
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
There is an onClick and onLongClick listener for each view :
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
FloatingActionButton actionButton = findViewById(R.id.actionButton);
actionButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// start your activity from here
return true;
}
});
}

How can I show image in Recyclerview - Recyclerview image display error

Firstly sorry if my english explanation is bad. My issue is, I am trying to make weather app and I want to show 5 day forecast.I keep the data in arraylist that I pull in api and send to my adapter class. As you know weahter icons are expressed as string in weather api. such as "010d" is sunny something like that.I am going to show recyclerview that I wrote 5 day forecast. Everything is working but icons doesn't show. I am sharing codes that I did.
I am getting data in forecast class
My forecast class
public class forecast extends AppCompatActivity {
ActivityResultLauncher<String> permissionLauncher;
LocationManager locationManager;
LocationListener locationListener;
ImageView forecast_back_icon;
RecyclerView recyclerviewforecast;
String API_KEY_FORECAST;
String URL_FORECAST;
Double Latitude,Longitude;
ArrayList<RecyclerviewModel> arrayList;
ForecastAdapter forecastAdapter;
public forecast(){
super();
}
public void init(){
arrayList = new ArrayList<>();
forecast_back_icon = findViewById(R.id.forecast_back_icon);
recyclerviewforecast = findViewById(R.id.RecyclerviewForecast);
get_forecast_data(Latitude,Longitude);
forecast_back_icon();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forecast);
Intent intent = getIntent();
Latitude = intent.getDoubleExtra("lat",0);
Longitude = intent.getDoubleExtra("long",0);
System.out.println("LATİTUDE "+Latitude+" Longitude "+Longitude);
init();
}
public void forecast_back_icon(){
forecast_back_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent IntentForecastToMain = new Intent(forecast.this,MainActivity.class);
startActivity(IntentForecastToMain);
}
});
}
public void get_forecast_data(Double Lat, Double Long){
//EXAMPLE URL
//https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API%20key}
API_KEY_FORECAST = "c29ecfafd4a70caad8fee38d6054bfc7";
URL_FORECAST = "https://api.openweathermap.org/data/2.5/onecall?lat="+Lat+"&lon="+Long+"&exclude=current,minutely,hourly,alerts&appid="+API_KEY_FORECAST;
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL_FORECAST, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray daily = response.getJSONArray("daily");
for(int i=0;i<daily.length();i++){
String temp = daily.getJSONObject(i).getJSONObject("temp").getString("day");
String feels_like = daily.getJSONObject(i).getJSONObject("feels_like").getString("day");
String pressure = daily.getJSONObject(i).getString("pressure");
String humidity = daily.getJSONObject(i).getString("humidity");
String wind_speed = daily.getJSONObject(i).getString("wind_speed");
String icon = daily.getJSONObject(i).getJSONArray("weather").getJSONObject(0).getString("icon");
String description = daily.getJSONObject(i).getJSONArray("weather").getJSONObject(0).getString("description");
arrayList.add(new RecyclerviewModel(temp,humidity,feels_like,pressure,description,wind_speed,icon));
}
}
catch (JSONException e) {
e.printStackTrace();
}
forecastAdapter = new ForecastAdapter(arrayList);
recyclerviewforecast.setAdapter(forecastAdapter);
recyclerviewforecast.setLayoutManager(new LinearLayoutManager(forecast.this));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(request);
System.out.println("forecast class arraylist size : --> "+arrayList.size());
}
}
My adapter class
public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.MyForecastViewHolder> {
ArrayList<RecyclerviewModel> ForecastArraylist;
ForecastDailyIconConverter forecastDailyIconConverter;
public ForecastAdapter(ArrayList<RecyclerviewModel> ForecastArraylist){
this.ForecastArraylist = ForecastArraylist;
System.out.println("ForecastAdapter arraylist size : --- > "+ForecastArraylist.size());
}
#NonNull
#Override
public MyForecastViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerviewForecastRowBinding recyclerviewForecastRowBinding = RecyclerviewForecastRowBinding.inflate(LayoutInflater.from(parent.getContext()),parent,false);
return new MyForecastViewHolder(recyclerviewForecastRowBinding);
}
#Override
public void onBindViewHolder(#NonNull MyForecastViewHolder holder, int position) {
System.out.println("we are in onbindviewholder.... ");
Double temperature = Double.parseDouble(ForecastArraylist.get(position).getTemperature()) - 273.15;
System.out.println(temperature);
Double feels_like = Double.parseDouble(ForecastArraylist.get(position).getFeels_like()) - 273.15;
holder.binding.txtRecyclerviewDay.setText("day "+(position+1));
holder.binding.txtRecyclerviewTemp.setText("temperature:"+temperature.toString().substring(0,4)+"°");
holder.binding.txtRecyclerviewFeelslike.setText("feels like:"+feels_like.toString().substring(0,4)+"°");
holder.binding.txtRecyclerviewHumidity.setText("humidity:%"+ForecastArraylist.get(position).getHumadity());
holder.binding.txtRecyclerviewPressure.setText("pressure:"+ForecastArraylist.get(position).getPressure()+"hPa");
holder.binding.txtRecyclerviewWindSpeed.setText("wind speed:"+ForecastArraylist.get(position).getWind_speed()+"km/h");
holder.binding.txtRecyclerviewCloud.setText(ForecastArraylist.get(position).getDescription());
String icon_id = ForecastArraylist.get(position).getId();
forecastDailyIconConverter = new ForecastDailyIconConverter();
int id1 = forecastDailyIconConverter.ConvertIntoNumeric(icon_id);
load_weather_icon(id1,holder);
}
public void load_weather_icon(int id1,MyForecastViewHolder holder){
if(id1>=200 && id1 <= 232){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.thunderstorm);
}
else if(id1>=300 && id1<= 321){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.showerrain);
}
else if(id1>=500 && id1<= 504){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.rain);
}
else if(id1 == 511){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.snow);
}
else if(id1>=520 && id1<= 531){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.showerrain);
}
else if(id1>=600 && id1<= 622){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.snow);
}
else if(id1>=701 && id1<= 781){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.mist);
}
else if(id1 == 800 ){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.clearsky);
}
else if(id1 == 801){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.fewclouds);
}
else if(id1 == 802){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.scatteredclouds);
}
else if(id1 == 803){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.brokenclouds);
}
else if(id1 == 804){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.brokenclouds);
}
}
#Override
public int getItemCount() {
return ForecastArraylist.size();
}
public class MyForecastViewHolder extends RecyclerView.ViewHolder{
private RecyclerviewForecastRowBinding binding;
public MyForecastViewHolder(#NonNull RecyclerviewForecastRowBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
}
I have tried to write icons in onbindviewholder without load_weather_icon() funct and it hasn't worked
My recyclerview_row xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100"
android:background="#FA8072"
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical"
android:padding="5dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_weight="40"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
>
<TextView
android:id="#+id/txt_recyclerview_day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="day:"
android:textColor="#color/white"
></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
>
<TextView
android:id="#+id/txt_recyclerview_temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="temp:"
android:textColor="#color/white"
></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
>
<TextView
android:id="#+id/txt_recyclerview_feelslike"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="feels like:"
android:textColor="#color/white"></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="#+id/txt_recyclerview_pressure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="pressure:"
android:textColor="#color/white"></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="#+id/txt_recyclerview_humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="humidity:"
android:textColor="#color/white"></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="#+id/txt_recyclerview_wind_speed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="wind speed:"
android:textColor="#color/white"></TextView>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="60"
android:layout_margin="5dp"
android:padding="5dp"
android:gravity="right"
android:orientation="vertical"
>
<ImageView
android:id="#+id/recyclerview_cloud_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
></ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txt_recyclerview_cloud"
android:text=""
android:gravity="center"
android:layout_margin="5dp"
android:padding="5dp"
android:textColor="#color/white"
></TextView>
</LinearLayout>
enter image description here
Use Glide or Picasso library
They are best in these type of Application

unable to make proper ui like playstore

Hi i am developing an app where i have to make a ui like playtstore for that i saw this tutorial but now my problem is that i'm unable to add different
text for different rows and second is that even after setting height and width it doesnt seem to be get affected.
Please if someone can help me out here i'm stuck at this point
my code is as follows
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int[] images = {R.drawable.vancouver,R.drawable.party,R.drawable.hands_ip,R.drawable.dj};
// Inflate the layout for this fragment
allSampleData = new ArrayList<SectionDataModel>();
createDummyData();
HorizontalAdapter firstAdapter = new HorizontalAdapter(images);
View view = inflater.inflate(R.layout.fragment_home, container, false);
NestedScrollView nestedScrollView = view.findViewById(R.id.scrollView);
llm = new LadderLayoutManager(1.5f, 0.85f, LadderLayoutManager.HORIZONTAL).
setChildDecorateHelper(new LadderLayoutManager
.DefaultChildDecorateHelper(getResources().getDimension(R.dimen.item_max_elevation)));
llm.setChildPeekSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
30, getResources().getDisplayMetrics()));
//llm.setReverse(true);
/*llm.setMaxItemLayoutCount(5);
rcv = (RecyclerView) view.findViewById(R.id.rcv);
rcv.setLayoutManager(llm);
new LadderSimpleSnapHelper().attachToRecyclerView(rcv);
adapter = new HSAdapter();
rcv.setAdapter(adapter);
multi_scroll_recyclerview = (RecyclerView)view.findViewById(R.id.multi_scroll_recyclerview);
multi_scroll_recyclerview.setNestedScrollingEnabled(false);
multi_scroll_layout_manager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
multi_scroll_recyclerview.setLayoutManager(multi_scroll_layout_manager);
multi_scroll_adapter = new RecyclerViewDataAdapter(getActivity(),allSampleData);
multi_scroll_recyclerview.setAdapter(multi_scroll_adapter);
multi_scroll_recyclerview.setHasFixedSize(true);*/
/* MultiSnapRecyclerView firstRecyclerView = (MultiSnapRecyclerView)view.findViewById(R.id.first_recycler_view);
LinearLayoutManager firstManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
firstRecyclerView.setLayoutManager(firstManager);
firstRecyclerView.setAdapter(firstAdapter);
HorizontalAdapter secondAdapter = new HorizontalAdapter(images);
MultiSnapRecyclerView secondRecyclerView =(MultiSnapRecyclerView) view.findViewById(R.id.second_recycler_view);
LinearLayoutManager secondManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
secondRecyclerView.setLayoutManager(secondManager);
secondRecyclerView.setAdapter(secondAdapter);
HorizontalAdapter thirdAdapter = new HorizontalAdapter(images);
MultiSnapRecyclerView thirdRecyclerView = (MultiSnapRecyclerView)view.findViewById(R.id.third_recycler_view);
LinearLayoutManager thirdManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
thirdRecyclerView.setLayoutManager(thirdManager);
thirdRecyclerView.setAdapter(thirdAdapter);*/
return view;
}
public void createDummyData() {
for (int i = 1; i <= 5; i++) {
SectionDataModel dm = new SectionDataModel();
dm.setHeaderTitle("Clubs");
dm.setHeadertitle2("Lounge");
dm.setHeadertitle3("Cafe");
dm.setHeadertitle4("Rooftop");
ArrayList<SingleItemModel> singleItem = new ArrayList<SingleItemModel>();
for (int j = 0; j <= 5; j++) {
singleItem.add(new SingleItemModel("Item " + j, "URL " + j));
}
dm.setAllItemsInSection(singleItem);
allSampleData.add(dm);//line which is causing issue
}
}
code for adapter
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SingleItemModel> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModel singleItem = itemsList.get(i);
holder.tvTitle.setText(singleItem.getName());
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView tvTitle;
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.itemImage);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
My code for model class
public class SectionDataModel {
private String headerTitle,headertitle2,headertitle3,headertitle4;
private ArrayList<SingleItemModel> allItemsInSection;
public SectionDataModel() {
}
public SectionDataModel(String headerTitle, ArrayList<SingleItemModel> allItemsInSection) {
this.headerTitle = headerTitle;
this.allItemsInSection = allItemsInSection;
}
public String getHeaderTitle() {
return headerTitle;
}
public String getHeadertitle2() {
return headertitle2;
}
public String getHeadertitle3() {
return headertitle3;
}
public String getHeadertitle4() {
return headertitle4;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public void setHeadertitle2(String headertitle2) {
this.headertitle2 = headertitle2;
}
public void setHeadertitle3(String headertitle3) {
this.headertitle3 = headertitle3;
}
public void setHeadertitle4(String headertitle4) {
this.headertitle4 = headertitle4;
}
public ArrayList<SingleItemModel> getAllItemsInSection() {
return allItemsInSection;
}
public void setAllItemsInSection(ArrayList<SingleItemModel> allItemsInSection) {
this.allItemsInSection = allItemsInSection;
}
}
listitem.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:selectableItemBackground"
android:orientation="vertical"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.ct.listrtrial.Custom.CustomTextViewMedium
android:id="#+id/itemTitle"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_toLeftOf="#+id/btnMore"
android:text="Sample title"
android:textColor="#android:color/white"
android:textSize="27sp" />
<ImageView
android:id="#+id/btnMore"
android:layout_width="0dp"
android:layout_weight="0.8"
android:layout_marginTop="13dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#drawable/ic_more_horiz_black_24dp"
android:textColor="#FFF" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_height="160dp"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</LinearLayout>
main fragment.xml
<android.support.v4.widget.NestedScrollView android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/scrollView"
android:fillViewport="true"
android:background="#color/colorPrimary"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:paddingBottom="10dp"
android:paddingTop="10dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/multi_scroll_recyclerview"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1">
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
listsinglecard.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="220dp"
android:layout_marginLeft="18dp"
android:layout_height="200dp"
app:cardCornerRadius="65dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:selectableItemBackground"
android:orientation="vertical">
<ImageView
android:id="#+id/itemImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:scaleType="centerCrop"
android:src="#drawable/vancouver" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/itemImage"
android:gravity="center"
android:padding="5dp"
android:visibility="gone"
android:text="Sample title"
android:textColor="#android:color/black"
android:textSize="18sp" />
</LinearLayout>
</android.support.v7.widget.CardView>

Recycler's custom adapter methods are not called

i am using other layout elements and recyclerview in a layout and inflating cardview layout in oncreateViewHolder (custom adapter). Methods are only called when i just user recyclerview in a layout not with other layout elements.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_layout_for_item_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/detail_card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/detail_category_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:textStyle="bold"
android:layout_below="#+id/detail_category_price" />
<TextView
android:id="#+id/detail_category_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="Rs: 1000" />
<Button
android:id="#+id/btn_bid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bid"
android:textColor="#color/colorPrimary"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/detail_category_price"
android:layout_margin="10dp"/>
<GridView
android:id="#+id/grid_view"
android:layout_below="#+id/btn_bid"
android:columnWidth="100dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</GridView>
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:id="#+id/view"
android:layout_marginTop="5dp"
android:layout_below="#+id/grid_view"
android:background="#000000" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="About the seller"
android:layout_margin="5dp"
android:textSize="20sp"
android:textColor="#color/orange"
android:id="#+id/about_seller"
android:layout_below="#+id/view"
/>
<TextView
android:id="#+id/seller_user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="username: bilal"
android:layout_margin="5dp"
android:layout_below="#+id/about_seller"/>
<Button
android:id="#+id/contact_seller_button"
android:text="contact button"
android:layout_margin="5dp"
android:layout_below="#+id/seller_user_name"
android:textColor="#color/colorPrimary"
android:shadowColor="#color/orange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.RecyclerView
android:id="#+id/bids_recycler_view"
android:layout_width="match_parent"
android:layout_below="#+id/detail_card_view"
android:layout_height="200dp"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
here is the layout that i am inflating
<android.support.v7.widget.CardView
android:layout_margin="5dp"
android:id="#+id/card_view"
android:layout_gravity="center"
android:background="#android:color/white"
app:cardElevation="2sp"
app:cardUseCompatPadding="true"
android:layout_width="match_parent"
android:layout_height="200dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/bid_text_View"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="$10000"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#android:color/black"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/bidder_user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bidder Name"
android:textStyle="italic"
android:textSize="16sp"
android:textColor="#android:color/black"
android:layout_below="#+id/bid_text_View"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</ScrollView>
here is the activity code ->
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private BidsAdapter mBidsAdapter;
private ArrayList<String> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_detials);
String detail = getIntent().getStringExtra(AppGlobals.detial);
setTitle(detail);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = (RecyclerView)findViewById(R.id.bids_recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout_for_item_detail);
mSwipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green,
R.color.colorPrimary, R.color.gray);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(false);
}
});
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.canScrollVertically(LinearLayoutManager.VERTICAL);
bitmapArrayList = new ArrayList<>();
arrayList = new ArrayList<>();
arrayList.add("test one");
arrayList.add("test two");
arrayList.add("test three");
arrayList.add("test four");
arrayList.add("test five");
}
#Override
protected void onResume() {
super.onResume();
mBidsAdapter = new BidsAdapter(arrayList);
mRecyclerView.setAdapter(mBidsAdapter);
System.out.println(mRecyclerView == null);
System.out.println(mBidsAdapter == null);
mRecyclerView.addOnItemTouchListener(new BidsAdapter(arrayList, getApplicationContext()
, new BidsAdapter.OnItemClickListener() {
#Override
public void onItem(String item) {
System.out.println(item);
}
}));
System.out.println("DONE");
}
static class BidsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements
RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
private BidView bidView;
private ArrayList<String> items;
public interface OnItemClickListener {
void onItem(String item);
}
public BidsAdapter(ArrayList<String> data) {
super();
this.items = data;
}
public BidsAdapter(ArrayList<String> categories, Context context, OnItemClickListener listener) {
this.items = categories;
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
System.out.println("beforeView");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bids_layout, parent, false);
System.out.println(view == null);
bidView = new BidView(view);
System.out.println("WORKING");
return bidView;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
bidView.textView.setText(String.valueOf(position));
bidView.bidderTextView.setText(items.get(position));
System.out.println(position);
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View childView = rv.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItem(items.get(rv.getChildPosition(childView)));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
#Override
public int getItemCount() {
return items.size();
}
}
static class BidView extends RecyclerView.ViewHolder {
public TextView textView;
public TextView bidderTextView;
public BidView(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.bid_text_View);
bidderTextView = (TextView) itemView.findViewById(R.id.bidder_user_name);
}
}
you replace this
static class BidsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements
RecyclerView.OnItemTouchListener {
instead
static class BidsAdapter extends RecyclerView.Adapter<BidsAdapter.BidView> implements
RecyclerView.OnItemTouchListener {

android - MapFragment inside ScrollView inside Fragment

My goal is to let MapFragment handle touch event instead of ScrollView.
MapFragment is being added programmatically inside of ScrollView which is inside of Fragment.
<ScrollView
android:id="#+id/scrollview_event"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#id/button_create"
android:layout_alignParentTop="true" >
<LinearLayout
android:id="#+id/linearlayout_event"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_light"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearlayout_where"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/linearlayout_header_event"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textview_where"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="#string/where"
android:textColor="#color/text_dark"
android:textSize="#dimen/text_heading" />
<View
android:id="#+id/view_divider_where"
android:layout_width="match_parent"
android:layout_height="1px"
android:layout_below="#id/textview_where"
android:layout_marginLeft="10dp"
android:layout_marginRight="30dp"
android:background="#color/bg_dark" />
<ImageView
android:id="#+id/imageview_close_event"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_margin="5dp"
android:clickable="true"
android:onClick="onClickCloseEvent"
android:src="#drawable/close_dark" />
</RelativeLayout>
<FrameLayout
android:id="#+id/framelayout_map"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginTop="10dp" >
<FrameLayout
android:id="#+id/fragment_map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/imageview_center_event"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="top"
android:layout_margin="6dp"
android:background="#color/bg_transparent_light"
android:clickable="true"
android:padding="6dp"
android:src="#drawable/event_pin" />
<ImageView
android:id="#+id/imageview_my_position"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="bottom|left"
android:layout_margin="6dp"
android:background="#color/bg_transparent_light"
android:clickable="true"
android:padding="6dp"
android:src="#drawable/gps_target" />
</FrameLayout>
<TextView
android:id="#+id/textview_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#color/bg_dark"
android:padding="6dp"
android:textColor="#color/text_light"
android:textSize="#dimen/text_address"
android:visibility="visible" />
</LinearLayout>
//other views and layouts...
</LinearLayout>
</ScrollView>
mapFragment = new FragmentMap();
getChildFragmentManager().beginTransaction().add(R.id.fragment_map, mapFragment, TAG).commit();
getChildFragmentManager().executePendingTransactions();
FragmentMap looks like this:
public class FragmentMap extends SupportMapFragment {
private OnTouchListener mListener;
private boolean mTouchListener = false;
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstance) {
View layout = super.onCreateView(layoutInflater, viewGroup, savedInstance);
TouchableWrapper frameLayout = new TouchableWrapper(getActivity());
frameLayout.setBackgroundColor(getResources().getColor(android.R.color.transparent));
frameLayout.addView(layout);
setListener(new OnTouchListener() {
#Override
public void onTouch() {
//Prevents NullPointerException
}
});
return frameLayout;
}
public void setListener(OnTouchListener listener) {
mListener = listener;
}
public interface OnTouchListener {
public abstract void onTouch();
}
public boolean getTouch() {
return mTouchListener;
}
public class TouchableWrapper extends FrameLayout {
public TouchableWrapper(Context context) {
super(context);
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTouchListener = true;
break;
case MotionEvent.ACTION_UP:
mTouchListener = false;
break;
}
mListener.onTouch();
return super.dispatchTouchEvent(event);
}
}
}
I set listener on a map:
mapFragment.setListener(new FragmentMap.OnTouchListener() {
#Override
public void onTouch() {
scrollView.requestDisallowInterceptTouchEvent(true);
}
});
This is supposed to work when map fragment is declared in the XML layout but when I am adding it programmatically, it doesn't.
To enable or disable intercepting event in a parent view, you have Android's onInterceptTouchEvent(MotionEvent ev) method. But it is propagated from the top-down (i.e. the parent view returns true if it consumed the event, false otherwise) . So create a class extending the ScrollView, and override that method:
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if(checkCoordinateCross(ev, YOUR_TARGET_VIEW_ID)) {
return false;
}
return true;
}
private boolean checkCoordinateCross(MotionEvent ev, int resId) {
View target = findViewById(resId);
if(target == null) {
return false;
}
if(ev.getX() > target.getX() && ev.getX() < target.getX() + target.getWidth() && ev.getY() > target.getY() && ev.getY() < target.getY() + target.getHeight()) {
return true;
}
return false;
}
Note that YOUR_TARGET_VIEW_ID has to be the child of the ScrollView or findViewById(...) will return null.

Categories

Resources