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.
Related
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....
I'm trying to create a form to capture data, I need to access the camera to take pictures. My problem is when I try to call the camera with imagenButton, it's not working but the code doesn't show any error.
Here's my fragment to declare form:
public class EspecimenesInsertarFragment extends Fragment implements
Response.Listener<JSONObject>, Response.ErrorListener {
private EspecimenesViewModel especimenesViewModel;
RequestQueue rq;
JsonRequest jrq;
final int COD_SELECCIONA=10;
final int COD_FOTO=20;
private static final int REQUEST_IMAGE_CAMERA=101;
private static final int REQUEST_PERMISSION_CAMERA=101;
Button btnGuardar, btnCancelar;
ImageButton btnCamara, btnGaleria;
ImageView imageView;
public static final int MY_DEFAULT_TIMEOUT = 50000;
public EspecimenesInsertarFragment() {
// Required empty public constructor
}
public static EspecimenesInsertarFragment newInstance() { return new EspecimenesInsertarFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view;
view = inflater.inflate(R.layout.fragment_colecciones_insertar, container, false);
imageView = (ImageView)view.findViewById(R.id.imageView);
btnCamara=(ImageButton) view.findViewById(R.id.tomarFoto);
btnGuardar = (Button) view.findViewById(R.id.buttonIngresarEspecimenes);
rq = Volley.newRequestQueue(getContext());
/* if(validaPermisos()){
btnCamara.setEnabled(true);
}else{
btnCamara.setEnabled(false);
} */
if (ContextCompat.checkSelfPermission(getContext(), WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA}, 1000);
}
btnGuardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registrar_especimen("http://localhost/BIO-UES-APP/EspecimenesController.php");
}
});
static final int REQUEST_TAKE_PHOTO=1;
public void tomarFoto(View view){
Intent takePictureInent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Log.d("entra","");
if(takePictureInent.resolveActivity(getActivity().getPackageManager())!= null){
File photoFile=null;
try {
photoFile=createImageFile();
}catch (IOException ex){
}
if(photoFile!=null){
Uri photoUri=FileProvider.getUriForFile(getActivity(),"com.example.luvin.drawercero",photoFile);
takePictureInent.putExtra(MediaStore.EXTRA_OUTPUT,photoUri);
getActivity().startActivityForResult(takePictureInent,REQUEST_TAKE_PHOTO);
}
}
}
And this is my XML layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Especimenes.EspecimenesConsultarFragment">
<!-- TODO: Update blank fragment layout -->
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_centerVertical="true"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="0dp"
android:layout_marginEnd="-7dp"
android:layout_marginRight="-7dp"
android:layout_marginBottom="9dp"
tools:layout_editor_absoluteX="393dp"
tools:layout_editor_absoluteY="79dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<ImageButton
android:id="#+id/tomarFoto"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginStart="100dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"
android:clickable="true"
android:src="#android:drawable/ic_menu_camera" />
<ImageButton
android:id="#+id/seleccionarDesdeGaleria"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginStart="200dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"
android:src="#android:drawable/ic_menu_gallery" />
</FrameLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="88dp"
android:orientation="vertical">
<Button
android:id="#+id/buttonCancelarEspecimenes"
android:layout_width="129dp"
android:layout_height="41dp"
android:layout_toRightOf="#+id/buttonIngresar"
android:backgroundTint="#96A6A8"
android:gravity="center|left"
android:text="CANCELAR"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.783"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.659" />
<Button
android:id="#+id/buttonIngresarEspecimenes"
android:layout_width="129dp"
android:layout_height="41dp"
android:layout_marginStart="68dp"
android:text="INGRESAR"
app:backgroundTint="#00BCD4"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/buttonCancelar"
app:layout_constraintHorizontal_bias="0.85"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.659" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</ScrollView>
Logcat message when button is pressed:
com.example.luvin.drawercero D/ViewRootImpl#6731d38[MainActivity]: ViewPostIme pointer 1
To complete my question, I have the permissions in the manifest. I already tried to call the camera in another way, tried creating the method in the MainActivity to create the OnClick event in the XML Layout, but nothing works.
If anyone knows how to solve this issue please help.
Thanks.
You forgot to add the on click listener to your photo button. This should solve your problem:
btnCamara = view.findViewById(R.id.tomarFoto);
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tomarFoto(v);
}
});
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 {
I have an adapter with buttons and text views. It represents friend requests.
TextView text would be : Do you want to accept X as your friend?
There are 2 buttons : one for accepting, one for declining. Pressing Decline, it would just remove the row from the ListView, while pressing accept will change the text into: X and Y are now friends.
My question is how can I get the position of the row and change it on button press and also save the View for next time I access it?
Adapter : At the moment I don't have proper data structure for the adapter, so for testing purposes, just using a String:
public class FriendRequestAdapter extends BaseAdapter {
String mName;
Context mContext;
public FriendRequestAdapter(String name, Context context) {
this.mName = name;
this.mContext = context;
}
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.friend_request_layout, null);
}
TextView sender_name = (TextView) convertView.findViewById(R.id.wannabe_name);
if (mName.length() > 11) {
mName = mName.substring(0, 12);
}
sender_name.setText(mName);
ImageButton friend_request_accepted = (ImageButton) convertView.findViewById(R.id.accept_friend_request);
friend_request_accepted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
new APIService().confirmInvite();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
}
});
return convertView;
}
Inflated Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/changing_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/check_in_map_menu"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:id="#+id/friend_image_container"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="7dp"
android:background="#drawable/polaroid_frame_friend_list">
<ImageView
android:id="#+id/facebook_friend_pic"
android:layout_width="55dp"
android:layout_height="45dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:background="#drawable/category_explore"/>
<TextView
android:id="#+id/name_facebook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/facebook_friend_pic"
android:layout_centerHorizontal="true"
android:text="dummy"
android:textColor="#color/enloop_dark_gray"
android:textSize="9sp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:layout_toRightOf="#+id/friend_image_container">
<TextView
android:id="#+id/wannabe_name"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:text="dada"
android:textColor="#color/enloop_dark_gray"
android:textSize="15dp"/>
<TextView
android:id="#+id/facebook_friend_name"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/wannabe_name"
android:text=" has sent you a request"
android:textColor="#color/enloop_dark_gray"
android:textSize="15dp"/>
<ImageButton
android:id="#+id/later_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:background="#drawable/btn_nothanks"
android:clickable="false"
android:focusable="false"/>
<ImageButton
android:id="#+id/accept_friend_request"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:layout_toRightOf="#+id/later_button"
android:background="#drawable/btn_accept_text"
android:clickable="false"
android:focusable="false"/>
<ImageButton
android:id="#+id/invite_facebook_friends"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="#drawable/btn_delete_notification"
android:clickable="false"
android:focusable="false"/>
</RelativeLayout>
</RelativeLayout>
Following some tutorials, I managed to make a custom list.
But the whole screen is just a list
And now want to put the list below the form. And to make the whole screen make scroll along with the list (see the last item in the list, the form needs to rise)
The log (Toasty) says that the item was added, but nothing appears. I do not know if the problem is in how I add, or is the way I try to display
This is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:fillViewport="true"
android:padding="5dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/cliente" />
<EditText
android:id="#+id/venda_form_cliente"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:cursorVisible="false"
android:focusable="false"
android:hint="#string/selecione_um_cliente" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/produto" />
<EditText
android:id="#+id/venda_form_prod"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:cursorVisible="false"
android:focusable="false"
android:hint="#string/selecione_um_produto" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/quantidade" />
<EditText
android:id="#+id/venda_form_qtd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:selectAllOnFocus="true"
android:text="#string/um" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/valor" />
<EditText
android:id="#+id/venda_form_valor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:focusable="false"
android:inputType="none" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/desconto" />
<EditText
android:id="#+id/venda_form_desc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:selectAllOnFocus="true"
android:text="#string/zero" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/subtotal" />
<EditText
android:id="#+id/venda_form_subtotal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:focusable="false"
android:inputType="none" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/venda_form_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="#string/adicionar" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="none" >
</ListView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
And my activity
public class VendaFormActivity extends Activity {
private Cliente cliente;
// private Spinner condicaoSelect;
private Produto produto;
private TextWatcher somar;
private ItemVenda itemVenda;
private ListaAdapter listaAdapter;
private EditText inputQuantidade;
private EditText inputDesconto;
private EditText inputSubTotal;
private EditText inputProduto;
private EditText inputValor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_venda_form);
inputProduto = ((EditText) findViewById(R.id.venda_form_prod));
inputValor = ((EditText) findViewById(R.id.venda_form_valor));
((EditText) findViewById(R.id.venda_form_cliente)).setOnClickListener(new ClickListener(this, ClienteActivity.class, MainActivity.REQUEST_CLIENTE));
inputProduto.setOnClickListener(new ClickListener(this, ProdutoActivity.class, MainActivity.REQUEST_PRODUTO));
//condicaoSelect = (Spinner) findViewById(R.id.venda_form_condicao);
//new CondicaoHelper(this).popular(condicaoSelect);
bindCamposValores();
fazerLista();
bindBtnAdd();
}
private void limparCamposValores() {
inputDesconto.setText("0.00");
inputQuantidade.setText("1");
inputSubTotal.getText().clear();
inputProduto.getText().clear();
}
private void bindBtnAdd() {
((Button) findViewById(R.id.venda_form_btn)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try{
Double quantidade = Double.parseDouble( inputQuantidade.getText().toString() );
Double desconto = Double.parseDouble( inputDesconto.getText().toString() );
itemVenda = new ItemVenda();
itemVenda.setDesconto(desconto);
itemVenda.setProduto(produto);
itemVenda.setQuantidade(quantidade);
listaAdapter.setNotifyOnChange(true);
listaAdapter.getItens().add(itemVenda);
listaAdapter.notifyDataSetChanged();
Toast.makeText(getApplication(), "Foi", Toast.LENGTH_SHORT).show();
limparCamposValores();
} catch (Exception e) {
Toast.makeText(getApplication(), "Invalido", Toast.LENGTH_SHORT).show();
// NPE no produto
// NumberFormat nos valores
}
}
});
}
private void fazerLista() {
listaAdapter = new ListaAdapter(getApplicationContext());
((ListView) findViewById(android.R.id.list)).setAdapter(listaAdapter);
}
static class ViewHolder {
protected TextView descricao;
protected TextView codigo;
protected TextView ean;
protected TextView referencia;
protected TextView quantidade;
protected TextView valor_unit;
protected TextView valor_item;
}
private class ListaAdapter extends ArrayAdapter<ItemVenda>{
private final Context context;
private final List<ItemVenda> itens;
public ListaAdapter(Context context) {
super(context, R.layout.produto_list);
this.context = context;
this.itens = new LinkedList<ItemVenda>();
}
public ListaAdapter(Context context, List<ItemVenda> itens) {
super(context, R.layout.produto_list, itens);
this.context = context;
this.itens = itens;
}
public List<ItemVenda> getItens() {
return itens;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflator.inflate(R.layout.produto_list_item, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.descricao = (TextView) view.findViewById(R.id.descricao);
viewHolder.codigo = (TextView) view.findViewById(R.id.codigo);
viewHolder.ean = (TextView) view.findViewById(R.id.ean);
viewHolder.referencia = (TextView) view.findViewById(R.id.referencia);
viewHolder.quantidade = (TextView) view.findViewById(R.id.quantidade);
viewHolder.valor_unit = (TextView) view.findViewById(R.id.valor_unit);
viewHolder.valor_item = (TextView) view.findViewById(R.id.valor_item);
view.setTag(viewHolder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
ItemVenda item = itens.get(position);
holder.descricao.setText(item.getProduto().getNome());
holder.codigo.setText(item.getProduto().getCodigo());
holder.ean.setText(item.getProduto().getEan());
holder.referencia.setText(item.getProduto().getReferencia());
holder.quantidade.setText(item.getQuantidade().toString());
holder.valor_unit.setText(item.getProduto().getPreco().toString());
holder.valor_item.setText(item.getSubTotal().toString());
return view;
}
}
private void bindCamposValores() {
inputQuantidade = ((EditText) findViewById(R.id.venda_form_qtd));
inputDesconto = ((EditText) findViewById(R.id.venda_form_desc));
inputSubTotal = ((EditText) findViewById(R.id.venda_form_subtotal));
somar = new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
Double sub = 0.0;
try{
itemVenda = new ItemVenda();
itemVenda.setQuantidade(Double.parseDouble(inputQuantidade.getText().toString()));
itemVenda.setDesconto(Double.parseDouble(inputDesconto.getText().toString()));
itemVenda.setProduto(produto);
sub = itemVenda.getSubTotal();
} catch (Exception e) {
// algum campo não é numero/está vazio
}
inputSubTotal.setText(""+sub);
}
};
// Se mudar o valor
inputQuantidade.addTextChangedListener(somar);
inputDesconto.addTextChangedListener(somar);
// quando sair do campo
inputQuantidade.setOnFocusChangeListener(new Focus("1"));
inputDesconto.setOnFocusChangeListener(new Focus("0.00"));
}
private class Focus implements OnFocusChangeListener {
private final String padrao;
public Focus(String padrao){
this.padrao = padrao;
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
Editable text = ((EditText) v).getText();
if(null == text || "".equals(text.toString())){
text.append(padrao);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_venda_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_copiar:
copiar();
return true;
case R.id.menu_simulacao:
simulacao();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void copiar() {
Toast.makeText(getApplication(), "Nada ainda", Toast.LENGTH_SHORT).show();
}
private void simulacao() {
Intent intent = new Intent(getApplicationContext(), SimulacaoPagtoActivity.class);
startActivityForResult(intent, MainActivity.REQUEST_SIMULACAO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == MainActivity.REQUEST_CLIENTE) {
if (resultCode == RESULT_OK) {
cliente = (Cliente) intent.getSerializableExtra(MainActivity.RESULT_MODEL_LIST);
((EditText) findViewById(R.id.venda_form_cliente)).setText(cliente.getNome());
}
} else if (requestCode == MainActivity.REQUEST_PRODUTO) {
if (resultCode == RESULT_OK) {
produto = (Produto) intent.getSerializableExtra(MainActivity.RESULT_MODEL_LIST);
inputProduto.setText(produto.getNome());
inputValor.setText(""+produto.getPreco());
somar.afterTextChanged(null);
}
} else if(requestCode == MainActivity.REQUEST_SIMULACAO){
// o que fazer quando voltar da simulação ?
}
}
}
Finally, my item layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="#+id/descricao"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#333"
android:textSize="16sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/codigo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="CODIGO" />
<TextView
android:id="#+id/ean"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="EAN" />
<TextView
android:id="#+id/referencia"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="REFERENCIA" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/quantidade"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="QUANT." />
<TextView
android:id="#+id/valor_unit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="VLR UNIT" />
<TextView
android:id="#+id/valor_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="VLR ITEM" />
</LinearLayout>
</LinearLayout>
UPDATE
When I add an item in the list, nothing is shown. But after I click a TextEdit, and the virtual keyboard up, after typing some value, I close the keyboard, then the adapter.getView () is called and the list appears
I think I found your problem. Shouldn't the following code:
((ListView) findViewById(android.R.id.list)).setAdapter(listaAdapter);
Be:
((ListView) findViewById(R.id.list)).setAdapter(listaAdapter);
instead?
You are trying to find a default Android view, rather than the view that you have created, which means that you are not actually setting the adapter for your ListView.
I am not sure about that, but if you want the list to be scrollable with the activity, you should use ScrollView, and then check if you scroll the list or the view itself. Try it
You can also try to see with debugger if the item was actually added to the list. I hope you will find an error.
Found the solution
1) The adapter have 2 constructors, but just 1 with List<ItemVenda> itens, and it isn't called.
I fixed it.
2) To add an item on the list, I need to call adapter.add() and not adapter.getItens().add()`. I think this trigger others methods.
3) Finally, to take the scroll list, and apply the scroll across the screen, I need to increase the size of the list. Then I override the method adapter.add(), and calculate the new height of the list, and add android:scrollbars="none" on ListView
Thanks to all, especially to #Marek