Hi I am using this library for my android bar code reader and it is working fine with activities but it give some what delay in initiate(Not smooth like when it use in the Activities)when use with the fragment any solution for this.
<RelativeLayout
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="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_gravity="top"
android:minHeight="?attr/actionBarSize"
android:background="#color/actionbar_opacity"
app:theme="#style/TransparentToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<RelativeLayout
android:id="#+id/btn_enable_qr"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginBottom="55dp"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:clickable="true"
android:layout_gravity="bottom"
android:background="#drawable/circle_layout_for_start_scan">
</RelativeLayout>
</RelativeLayout>
This is My Fragment & when application start I set this fragment to my main activity
public class ScannerFragment extends Fragment implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
private FrameLayout contentFrame;
RelativeLayout enableQR;
private static final int ZBAR_CAMERA_PERMISSION = 1;
public static ScannerFragment newInstance() {
return new ScannerFragment();
}
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = null;
try {
rootView = inflater.inflate(R.layout.activity_full_scanner, container, false);
contentFrame = (FrameLayout) rootView.findViewById(R.id.content_frame);
enableQR = (RelativeLayout) rootView.findViewById(R.id.btn_enable_qr);
enableQR.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
launchActivity();
break;
}
case MotionEvent.ACTION_UP: {
releaseCamera();
}
}
return true;
}
});
} catch (Exception e) {
// Log.e(TAG, "onCreateView: " + e.toString());
}
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
public void launchActivity() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.CAMERA}, ZBAR_CAMERA_PERMISSION);
} else {
setUpQrScanner();
}
}
public void setUpQrScanner() {
mScannerView = new ZBarScannerView(getActivity());
mScannerView.setFormats(BarcodeFormat.ALL_FORMATS);
contentFrame.addView(mScannerView);
mScannerView.setResultHandler(ScannerFragment.this);
mScannerView.startCamera(-1);
mScannerView.setAutoFocus(true);
}
public void releaseCamera() {
mScannerView.stopCamera();
contentFrame.removeView(mScannerView);
}
#Override
public void handleResult(Result rawResult) {
try {
scannerSoundAndVibration();
} catch (Exception e) {}
Toast.makeText(getActivity(), "Result" + rawResult.getContents()+" TYPE: "+rawResult.getBarcodeFormat().getId(), Toast.LENGTH_LONG).show();
}
#Override
public void onPause() {
super.onPause();
}
private void scannerSoundAndVibration() {
/**
* scanner sound alert time in millisecond
*/
final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 200);
tg.startTone(ToneGenerator.TONE_CDMA_KEYPAD_VOLUME_KEY_LITE);
/**
* scanner vibration alert time in millisecond
*/
Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(250);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case ZBAR_CAMERA_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setUpQrScanner();
} else {
Toast.makeText(getActivity(), "Please grant camera permission to use the QR Scanner", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
Related
I am not able to display an image inside the imageview in fragment.
I have grant all the permission of storage.
Code executes without any error but doesn't display an image.
Am i doing anything wrong please help.
i have display whole code here.
public class PrescriptionUploadFragment extends Fragment implements View.OnClickListener {
private static final int REQUEST_PERMISSION_CODE = 111;
private static final int PICK_IMAGE_REQUEST = 1;
private ExtendedFloatingActionButton eFabUpload, eFabChooseFile;
private EditText etDescriptionUpload;
private ImageView imgPrescriptionUploads;
private ProgressBar pbPrescriptionUpload;
private ChangeFragment changeFragment;
private InternetCheck internetCheck;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private DatabaseReference mDatabaseReference;
private StorageReference mStorageReference, ref;
private String UserID = "";
private Uri mImageUri;
private String id;
public PrescriptionUploadFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
UserID = mUser.getUid();
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Prescription").child(UserID);
mStorageReference = FirebaseStorage.getInstance().getReference("Prescription").child(UserID);
internetCheck = new InternetCheck(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_prescription_upload, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
InitializeViews(view);
}
private void InitializeViews(View view) {
eFabUpload = (ExtendedFloatingActionButton) view.findViewById(R.id.fabUploadPrescription);
eFabUpload.setOnClickListener(this);
eFabChooseFile = (ExtendedFloatingActionButton) view.findViewById(R.id.fabChooseFile);
eFabChooseFile.setOnClickListener(this);
etDescriptionUpload = (EditText) view.findViewById(R.id.etDescriptionUplaod);
pbPrescriptionUpload = (ProgressBar) view.findViewById(R.id.pbPrescriptionUpload);
imgPrescriptionUploads = (ImageView) view.findViewById(R.id.imgPrescriptionUploads);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
changeFragment = (ChangeFragment) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement MyInterface");
}
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fabChooseFile:
onClickChooseFile();
break;
case R.id.fabUploadPrescription:
onClickUploadPrescription();
break;
}
}
private void onClickChooseFile() {
if (CheckingPermissionIsEnabled()) {
Intent intentCamera = new Intent();
intentCamera.setType("image/*");
intentCamera.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intentCamera, PICK_IMAGE_REQUEST);
} else {
RequestMultiplePermission();
}
}
private void onClickUploadPrescription() {
if (mImageUri != null && internetCheck.checkConnection()){
id = mDatabaseReference.push().getKey();
ref = mStorageReference.child(id).child(System.currentTimeMillis() +"." + getExtension(mImageUri) );
ref.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
PrescriptionUpload prescriptionUpload = new PrescriptionUpload(id ,mImageUri ,
etDescriptionUpload.getText().toString().trim());
mDatabaseReference.child(id).setValue(prescriptionUpload).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
changeFragment.changeFrag("PRESCRIPTION_MAIN_FRAGMENT");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
pbPrescriptionUpload.setProgress((int) progress);
}
});
} else {
Toast.makeText(getActivity(), "Not an Image !", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
if (mImageUri != null){
imgPrescriptionUploads.setImageURI(mImageUri);
} else {
Toast.makeText(getActivity(), "Image not selected !", Toast.LENGTH_SHORT).show();
}
}
}
private String getExtension(Uri uri) {
ContentResolver cr = getActivity().getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cr.getType(uri));
}
public boolean CheckingPermissionIsEnabled() {
int FirstPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), INTERNET);
int FifthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), ACCESS_WIFI_STATE);
int EighthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), READ_EXTERNAL_STORAGE);
int NinthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), WRITE_EXTERNAL_STORAGE);
return FirstPermissionResult == PackageManager.PERMISSION_GRANTED &&
FifthPermissionResult == PackageManager.PERMISSION_GRANTED &&
EighthPermissionResult == PackageManager.PERMISSION_GRANTED &&
NinthPermissionResult == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSION_CODE:
if (grantResults.length > 0) {
boolean INTERNET = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean ACCESS_WIFI_STATE = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean READ_EXTERNAL_STORAGE = grantResults[2] == PackageManager.PERMISSION_GRANTED;
boolean WRITE_EXTERNAL_STORAGE = grantResults[3] == PackageManager.PERMISSION_GRANTED;
if (INTERNET && ACCESS_WIFI_STATE && READ_EXTERNAL_STORAGE && WRITE_EXTERNAL_STORAGE) {
Toast.makeText(getActivity(), "Permission Granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_LONG).show();
}
}
break;
}
}
private void RequestMultiplePermission() {
// Creating String Array with Permissions.
ActivityCompat.requestPermissions(getActivity(), new String[]
{
INTERNET,
ACCESS_WIFI_STATE,
READ_EXTERNAL_STORAGE,
WRITE_EXTERNAL_STORAGE
}, REQUEST_PERMISSION_CODE);
}
}
and xml code
<androidx.constraintlayout.widget.ConstraintLayout 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"
android:theme="#style/Theme.MaterialComponents"
tools:context=".PrescriptionUploadFragment">
<ImageView
android:id="#+id/imgPrescriptionUploads"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="24dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toTopOf="#+id/DescriptionUpload"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/DescriptionUpload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="16dp"
android:gravity="center"
app:layout_constraintBottom_toTopOf="#+id/pbPrescriptionUpload"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<EditText
android:id="#+id/etDescriptionUplaod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/et_description" />
</com.google.android.material.textfield.TextInputLayout>
<ProgressBar
android:id="#+id/pbPrescriptionUpload"
style="#style/Widget.MaterialProgressBar.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="16dp"
android:indeterminate="true"
app:layout_constraintBottom_toTopOf="#+id/linearLayout3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="16dp"
android:gravity="center"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="#+id/fabChooseFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginEnd="20dp"
android:background="#color/colorPrimaryDark"
android:backgroundTint="#color/colorPrimaryDark"
android:shadowColor="#color/colorPrimary"
android:text="#string/fabChooseFile"
android:textAlignment="center"
android:textColor="#color/colorText"
android:textColorLink="#color/colorPrimaryDark"
app:rippleColor="#color/colorText"
app:tint="#color/colorPrimaryDark" />
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="#+id/fabUploadPrescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:background="#color/colorPrimaryDark"
android:backgroundTint="#color/colorPrimaryDark"
android:shadowColor="#color/colorPrimary"
android:text="#string/fabUpload"
android:textAlignment="center"
android:textColor="#color/colorText"
android:textColorLink="#color/colorPrimaryDark"
app:rippleColor="#color/colorText"
app:tint="#color/colorPrimaryDark" />
</LinearLayout>
enter code here
I'm working on PlaceAutocompleteFragment. I load this Fragment Simply in the first time and when the load in a second time then show some error and its crashed.
Error is : java.lang.IllegalArgumentException: Binary XML file line
11: Duplicate id 0x7f090251, tag null, or parent id 0x7f090193 with another fragment for
com.google.android.gms.location.places.ui.PlaceAutocompleteFragment
public class MakeReservationFragment extends BaseFragment implements
GoogleApiClient.OnConnectionFailedListener , PlaceSelectionListener {
View mMakeReservationView;
ProgressBar bar;
FrameLayout layout;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new
LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
#Override
public View setContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mMakeReservationView = inflater.inflate(R.layout.frag_make_reservation, container, false);
initView();
return mMakeReservationView;
}
private void initView() {
setHeaderBarTitle("RESERVATION");
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getActivity().getFragmentManager().findFragmentById(R.id.place_fragment1);
autocompleteFragment.setOnPlaceSelectedListener(MakeReservationFragment.this);
autocompleteFragment.setHint("Search a Location");
autocompleteFragment.setBoundsBias(BOUNDS_GREATER_SYDNEY);
layout=(FrameLayout)mMakeReservationView.findViewById(R.id.framereserve1);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
setHeaderBarleftIcon(R.drawable.ic_home);
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
}
return false;
}
});
}
#Override
public void onPlaceSelected(Place place) {
}
#Override
public void onError(Status status) {
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode ==RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
onPlaceSelected(place,0);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
this.onError(status,0);
}
}
else
{
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
onPlaceSelected(place,1);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
onError(status,1);
}
}
}
private void onError(Status status, int i) {
Toast.makeText(getActivity(), "Place selection failed: " + status.getStatusMessage(),
Toast.LENGTH_SHORT).show();
}
private void onPlaceSelected(Place place, int i) {
try{
System.out.println("00000000 Place Darta IS 0 error" + place.getId()+","+place.getAddress()+","+place.getLatLng()+","+place.getLocale()+","+place.getName()+
","+place.getAttributions()+","+place.getViewport()+","+place.getPhoneNumber()+","+place.getPlaceTypes());
}
catch ( Exception e)
{
}
}
}
And XML code is:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/framereserve1"
android:background="#color/backgoound_dull"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/place_fragment1"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
android:layout_width="match_parent"
android:layout_height="50dp"/>
I have a Nested Scroll view and inside this, I have a Linear Layout that includes two recycler views. Now the problem is that the first recycler view is not expanding up to its full extent. i.e. there are 5 items in the first recycler view list but it is only showing the first item if I put wrap content. This should expand up to 5 items because of wrap content but it is not working. If I fixed the height to 200DP or 300dp then it started to show more items up to that height. However, I want to show all the items of the first recycler view and then when I scroll it should start second recycler view items after the first recycler view items end.
My layout is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
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="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:layout_marginTop="60dp"
android:orientation="vertical">
<com.sooryen.customview.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/spacing_normal"
android:text="#string/my_booking_latest_booking_lable"
app:font="avenirltstd_medium" />
<include layout="#layout/layout_divider" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_ongoing_bookings"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="android.support.v7.widget.LinearLayoutManager" />
<com.sooryen.customview.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:layout_margin="#dimen/spacing_normal"
android:text="#string/my_booking_past_booking_lable"
app:font="avenirltstd_medium" />
<include layout="#layout/layout_divider" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_past_bookings"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
android:layout_marginBottom="#dimen/spacing_extra_small"
android:scrollbars="none"
app:layoutManager="android.support.v7.widget.LinearLayoutManager" />
<View
android:layout_width="match_parent"
android:layout_height="150dp" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Please Help. Where I did something wrong. I tried so many ways from internet but nothing is working. Here is a screenshot of the this screen
The LABEL latest bookings has 5 items but it is only showing one and not expanding up to 5 items. However the second LABEL Past bookings is working perfectly and showing all items when i scroll up to end.
My java file is:
public class MyBookingActivity extends BaseToolBarActivity implements
SwipeRefreshLayout.OnRefreshListener {
int cancelValue;
private SwipeRefreshLayout swipeRefreshLayout;
#BindView(R.id.rv_ongoing_bookings)
RecyclerView mRVOngoingBookings;
private List<MyBookingsApi.ApiResponse.Datum> mCourtDataList = new ArrayList<>();
#BindView(R.id.rv_past_bookings)
RecyclerView mRVPastBookings;
private BaseRecyclerAdapter<MyBookingsApi.ApiResponse.Datum, MyBookingsViewHolder> mBaseRecyclerAdapterMyBookings = new BaseRecyclerAdapter<MyBookingsApi.ApiResponse.Datum, MyBookingsViewHolder>(MyBookingsViewHolder.class, R.layout.layout_list_item_my_bookings) {
#Override
protected void populateViewHolder(MyBookingsViewHolder itemViewHolder, final MyBookingsApi.ApiResponse.Datum model, int position) {
String date = null;
try {
date = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH).format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).parse(model.getDate()));
} catch (ParseException e) {
e.printStackTrace();
}
String sessions = "N.A.";
int CancelledValue = model.getCancelled();
if (CancelledValue == 0)
{
itemViewHolder.PaymentYesNo.setText(getString(R.string.booking_detail_no));
itemViewHolder.PaymentYesNo.setBackgroundResource(R.drawable.round_corner_linear_green);
}
else
{
itemViewHolder.PaymentYesNo.setText(getString(R.string.booking_detail_yes));
itemViewHolder.PaymentYesNo.setBackgroundResource(R.drawable.round_corner_linear_red);
}
String paymentConfirmed = model.getPayment_confirmed();
String paymentType = model.getPaymentType();
if (paymentConfirmed.equals("true"))
{
itemViewHolder.PaymentStatus.setText("Confirmed");
}
else
{
itemViewHolder.PaymentStatus.setText("Pending");
}
if (CancelledValue == 0 && paymentConfirmed.equals("false") && paymentType.equals("cash"))
{
itemViewHolder.DepositThisAmount.setText("Deposit " + String.valueOf(model.getDepositAmount()) + " SAR in " +
String.valueOf(model.getDepositTimeAllowed()) + " HRS");
}
else
{
itemViewHolder.DepositThisAmount.setVisibility(View.GONE);
}
if (model.getSession() != null)
sessions = model.getSession();
itemViewHolder.mCustomTextViewCourtBookingTime.setText(date + " " + sessions);
if (getResources().getConfiguration().locale.equals(new Locale("ar"))) {
itemViewHolder.mCustomTextViewCourtPrice.setText(model.getPrice() + " " + "ريال");
itemViewHolder.mCustomTextViewCourtCancellationCutoff.setText("يمكن الغاء الحجز قبل المباراة" + " : " + model.getCancelCutoffTime());
} else {
itemViewHolder.mCustomTextViewCourtPrice.setText(getString(R.string.price, model.getPrice()));
itemViewHolder.mCustomTextViewCourtCancellationCutoff.setText(getString(R.string.cancellation_cutoff, model.getCancelCutoffTime()));
}
String cancelshow = model.getCancelshow();
if (cancelshow.equals("true"))
{
cancelValue = 1;
itemViewHolder.mAppCompatImageViewMoreHoriz.setVisibility(View.VISIBLE);
}
else
{
cancelValue = 0;
itemViewHolder.mAppCompatImageViewMoreHoriz.setVisibility(View.GONE);
}
itemViewHolder.mCustomTextViewCourtName.setText(model.getCourtName());
itemViewHolder.mAppCompatImageViewMoreHoriz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MyBookingActivity.this, v);
popup.getMenu().add(0, 1, 0, getString(R.string.my_booking_cancel));
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case 1:
cancelBooking(model.getId());
break;
//case 1:
// deleteBooking(model.getId());
}
return false;
}
});
//displaying the popup
popup.show();
}
});
itemViewHolder.mReaRelativeLayoutMyBooking.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//launchActivity(MyBookingDetailActivity.getActivityIntent(MyBookingActivity.this, model.getId(), "MyBooking", 1));
}
});
itemViewHolder.mAppCompatImageViewRightArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchActivity(MyBookingDetailActivity.getActivityIntent(MyBookingActivity.this, model.getId(), "MyBooking", 1));
}
});
}
};
private BaseRecyclerAdapter<PastBookingsApi.ApiResponse.Datum, MyPastBookingsViewHolder> mBaseRecyclerAdapterMyPastBookings = new BaseRecyclerAdapter<PastBookingsApi.ApiResponse.Datum, MyPastBookingsViewHolder>(MyPastBookingsViewHolder.class, R.layout.layout_list_item_my_bookings) {
#Override
protected void populateViewHolder(MyPastBookingsViewHolder itemViewHolder, final PastBookingsApi.ApiResponse.Datum model, int position) {
String date = null;
try {
date = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH).format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).parse(model.getDate()));
} catch (ParseException e) {
e.printStackTrace();
}
String sessions = "N.A.";
int CancelledValue = model.getCancelled();
if (CancelledValue == 0)
{
itemViewHolder.PaymentYesNo.setText(getString(R.string.booking_detail_no));
itemViewHolder.PaymentYesNo.setBackgroundResource(R.drawable.round_corner_linear_green);
}
else
{
itemViewHolder.PaymentYesNo.setText(getString(R.string.booking_detail_yes));
itemViewHolder.PaymentYesNo.setBackgroundResource(R.drawable.round_corner_linear_red);
}
itemViewHolder.DepositThisAmount.setVisibility(View.GONE);
int paymentConfirmed = model.getPaymentConfirmed();
if (paymentConfirmed == 1)
{
itemViewHolder.PaymentStatus.setText("Confirmed");
}
else
{
itemViewHolder.PaymentStatus.setText("Pending");
}
if (model.getSession() != null)
sessions = model.getSession();
itemViewHolder.mCustomTextViewCourtBookingTime.setText(date + " " + sessions);
if (getResources().getConfiguration().locale.equals(new Locale("ar"))) {
itemViewHolder.mCustomTextViewCourtPrice.setText(model.getPrice() + " " + "ريال");
} else {
itemViewHolder.mCustomTextViewCourtPrice.setText(getString(R.string.price, model.getPrice()));
}
itemViewHolder.mCustomTextViewCourtCancellationCutoff.setText(getString(R.string.cancellation_cutoff, "0"));
itemViewHolder.mCustomTextViewCourtName.setText(model.getCourtName());
itemViewHolder.mAppCompatImageViewMoreHoriz.setVisibility(View.VISIBLE);
itemViewHolder.mAppCompatImageViewMoreHoriz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MyBookingActivity.this, v);
popup.getMenu().add(0, 1, 0, getString(R.string.notification_delete));
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case 1:
deleteBooking(model.getId());
break;
}
return false;
}
});
popup.show();
}
});
itemViewHolder.mAppCompatImageViewRightArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchActivity(MyBookingDetailActivity.getActivityIntent(MyBookingActivity.this, model.getId(), "MyBooking", 1));
}
});
itemViewHolder.mReaRelativeLayoutMyBooking.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// launchActivity(MyBookingDetailActivity.getActivityIntent(MyBookingActivity.this, model.getId(), "MyBooking", 1));
}
});
}
};
public static Intent getActivityIntent(Context context) {
return new Intent(context, MyBookingActivity.class);
}
private void cancelBooking(final int id) {
}
private void deleteBooking(final int id) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.title_activity_my_booking));
setUpRecyclerView();
setUpEmptyAdapter();
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
getMyBooking();
getMyPastBooking();
/*swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
getMyBooking();
}
}
);*/
}
private void setUpEmptyAdapter() {
mRVPastBookings.setAdapter(new BaseEmptyRecyclerAdapter<EmptyViewHolderRefresh>(EmptyViewHolderRefresh.class, R.layout.layout_place_holderrefresh) {
#Override
protected void populateEmptyViewHolder(EmptyViewHolderRefresh viewHolder) {
viewHolder.mAppCompatImageView.setImageResource(R.drawable.no_booking_place_holder);
viewHolder.mCustomTextViewTitle.setText(R.string.no_bookings_available_title);
viewHolder.mCustomTextViewDescription.setText(R.string.no_bookings_available_description);
viewHolder.refreshText.setText(R.string.swipe);
//viewHolder.mCustomButton.setText(R.string.try_again);
viewHolder.mCustomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getMyPastBooking();
}
});
}
});
mRVOngoingBookings.setAdapter(new BaseEmptyRecyclerAdapter<EmptyViewHolderRefresh>(EmptyViewHolderRefresh.class, R.layout.layout_place_holderrefresh) {
#Override
protected void populateEmptyViewHolder(EmptyViewHolderRefresh viewHolder) {
viewHolder.mAppCompatImageView.setImageResource(R.drawable.no_booking_place_holder);
viewHolder.mCustomTextViewTitle.setText(R.string.no_bookings_available_title);
viewHolder.mCustomTextViewDescription.setText(R.string.no_bookings_available_description);
//viewHolder.mCustomButton.setText(R.string.try_again);
viewHolder.refreshText.setText(R.string.swipe);
viewHolder.mCustomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getMyBooking();
}
});
}
});
}
private void setUpRecyclerView() {
mRVOngoingBookings.setAdapter(mBaseRecyclerAdapterMyBookings);
DividerItemDecoration mDividerItemDecorationMyBookings = new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);
mDividerItemDecorationMyBookings.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider));
mRVOngoingBookings.addItemDecoration(mDividerItemDecorationMyBookings);
mRVPastBookings.setAdapter(mBaseRecyclerAdapterMyPastBookings);
DividerItemDecoration mDividerItemDecorationMyPastBookings = new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);
mDividerItemDecorationMyPastBookings.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider));
mRVPastBookings.addItemDecoration(mDividerItemDecorationMyPastBookings);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finishWithResultCancel();
}
return super.onOptionsItemSelected(item);
}
#Override
protected int getMenuResource() {
return RESOURCE_NO_MENU;
}
#Override
protected int getLayoutResource() {
return R.layout.activity_my_booking;
}
#Override
public void onResume() {
super.onResume();
registerEventBus();
//getMyBooking();
//getMyPastBooking();
}
#Override
public void onPause() {
super.onPause();
unRegisterEventBus();
}
private void getMyPastBooking() {
/// swipeRefreshLayout.setRefreshing(true);
final ProgressDialog pd = new ProgressDialog(MyBookingActivity.this);
pd.setMessage("Please wait..");
pd.show();
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
pd.dismiss();
startApiService(PastBookingsApi.getServiceIntent(MyBookingActivity.this, getToken()));
}
}, 800);
}
private void getMyBooking() {
// swipeRefreshLayout.setRefreshing(true);
final ProgressDialog pd = new ProgressDialog(MyBookingActivity.this);
pd.setMessage("Please wait..");
pd.show();
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
pd.dismiss();
startApiService(MyBookingsApi.getServiceIntent(MyBookingActivity.this, getToken()));
}
}, 2000);
//swipeRefreshLayout.setRefreshing(false);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(BaseApi.EventBusMessage eventBusMessage) {
switch (eventBusMessage.event) {
case BaseApi.EventBusMessage.EVENT_SHOW_PROGRESS_DIALOG:
showProgressDialog();
break;
case BaseApi.EventBusMessage.EVENT_HIDE_PROGRESS_DIALOG:
hideProgressDialog();
break;
default:
if (eventBusMessage.object instanceof MyBookingsApi.ApiResponse)
parseMyBookingsSuccessResponse((MyBookingsApi.ApiResponse) eventBusMessage.object);
else if (eventBusMessage.object instanceof PastBookingsApi.ApiResponse) {
parsePastBookingsSuccessResponse((PastBookingsApi.ApiResponse) eventBusMessage.object);
} else if (eventBusMessage.object instanceof BaseApi.DefaultErrorResponse) {
parseErrorResponse((BaseApi.DefaultErrorResponse) eventBusMessage.object);
} else if (eventBusMessage.object instanceof BaseApi.Error500Response) {
//parseError500Response((BaseApi.Error500Response) eventBusMessage.object);
} else if (eventBusMessage.object instanceof MyBookingCancelApi.ApiResponse) {
parseCancelBookingSuccessResponse((MyBookingCancelApi.ApiResponse) eventBusMessage.object);
} else if (eventBusMessage.object instanceof MyBookingDeleteApi.ApiResponse) {
parseDeleteBookingSuccessResponse((MyBookingDeleteApi.ApiResponse) eventBusMessage.object);
}
break;
}
}
private void parseDeleteBookingSuccessResponse(MyBookingDeleteApi.ApiResponse apiResponse) {
showSnackBar(apiResponse.getMessage());
getMyPastBooking();
}
private void parseCancelBookingSuccessResponse(final MyBookingCancelApi.ApiResponse apiResponse) {
showSnackBar(apiResponse.getMessage());
getMyBooking();
/*final ProgressDialog pd = new ProgressDialog(MyBookingActivity.this);
pd.setMessage("Please wait..");
pd.show();
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
pd.dismiss();
startApiService(MyBookingDeleteApi.getServiceIntent(MyBookingActivity.this, getToken(), apiResponse.getData().getId()));
}
}, 800);*/
}
private void parsePastBookingsSuccessResponse(PastBookingsApi.ApiResponse apiResponse) {
List<PastBookingsApi.ApiResponse.Datum> datumList = apiResponse.getData();
if (datumList.size() > 0) {
Collections.sort(datumList, new Comparator<PastBookingsApi.ApiResponse.Datum>()
{
#Override
public int compare(PastBookingsApi.ApiResponse.Datum o1, PastBookingsApi.ApiResponse.Datum o2) {
return o1.getId() > o2.getId() ? -1 : (o1.getId() < o2.getId() ) ? 1 : 0;
}
});
mRVPastBookings.setAdapter(mBaseRecyclerAdapterMyPastBookings);
mBaseRecyclerAdapterMyPastBookings.setItems(datumList);
} else {
mRVPastBookings.setAdapter(new BaseEmptyRecyclerAdapter<EmptyViewHolderRefresh>(EmptyViewHolderRefresh.class, R.layout.layout_place_holderrefresh) {
#Override
protected void populateEmptyViewHolder(EmptyViewHolderRefresh viewHolder) {
viewHolder.mAppCompatImageView.setImageResource(R.drawable.no_booking_place_holder);
viewHolder.mCustomTextViewTitle.setText(R.string.no_bookings_available_title);
viewHolder.mCustomTextViewDescription.setText(R.string.no_bookings_available_description);
// viewHolder.mCustomButton.setText(R.string.try_again);
viewHolder.refreshText.setText(R.string.swipe);
viewHolder.mCustomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getMyPastBooking();
}
});
}
});
}
}
private void parseMyBookingsSuccessResponse(MyBookingsApi.ApiResponse apiResponse) {
// mCourtDataList = apiResponse.getData();
List<MyBookingsApi.ApiResponse.Datum> datumList = apiResponse.getData();
if (datumList.size() > 0) {
Collections.sort(datumList, new Comparator<MyBookingsApi.ApiResponse.Datum>()
{
#Override
public int compare(MyBookingsApi.ApiResponse.Datum o1, MyBookingsApi.ApiResponse.Datum o2) {
return o1.getId() > o2.getId() ? -1 : (o1.getId() < o2.getId() ) ? 1 : 0;
}
});
mRVOngoingBookings.setAdapter(mBaseRecyclerAdapterMyBookings);
mBaseRecyclerAdapterMyBookings.setItems(datumList);
} else {
mRVOngoingBookings.setAdapter(new BaseEmptyRecyclerAdapter<EmptyViewHolderRefresh>(EmptyViewHolderRefresh.class, R.layout.layout_place_holderrefresh) {
#Override
protected void populateEmptyViewHolder(EmptyViewHolderRefresh viewHolder) {
viewHolder.mAppCompatImageView.setImageResource(R.drawable.no_booking_place_holder);
viewHolder.mCustomTextViewTitle.setText(R.string.no_bookings_available_title);
viewHolder.mCustomTextViewDescription.setText(R.string.no_bookings_available_description);
//viewHolder.mCustomButton.setText(R.string.try_again);
viewHolder.refreshText.setText(R.string.swipe);
viewHolder.mCustomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getMyBooking();
}
});
}
});
}
}
private void parseError500Response(BaseApi.Error500Response error500Response) {
showAlertDialog(R.string.session_timeout_title, R.string.session_timeout_message, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
logout();
}
});
}
private void parseErrorResponse(BaseApi.DefaultErrorResponse defaultErrorResponse) {
showSnackBar(defaultErrorResponse.getMessage());
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void noInternet(String message) {
mRVOngoingBookings.setAdapter(new BaseEmptyRecyclerAdapter<EmptyViewHolderRefresh>(EmptyViewHolderRefresh.class, R.layout.layout_place_holderrefresh) {
#Override
protected void populateEmptyViewHolder(EmptyViewHolderRefresh viewHolder) {
viewHolder.mAppCompatImageView.setImageResource(R.drawable.no_internet_placeholder);
viewHolder.mCustomTextViewTitle.setText(R.string.connection_problem_title);
viewHolder.mCustomTextViewDescription.setText(R.string.connection_problem_description);
viewHolder.refreshText.setText(R.string.swipe);
//viewHolder.mCustomButton.setText(R.string.try_again);
viewHolder.mCustomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getMyBooking();
}
});
}
});
mRVPastBookings.setAdapter(new BaseEmptyRecyclerAdapter<EmptyViewHolderRefresh>(EmptyViewHolderRefresh.class, R.layout.layout_place_holderrefresh) {
#Override
protected void populateEmptyViewHolder(EmptyViewHolderRefresh viewHolder) {
viewHolder.mAppCompatImageView.setImageResource(R.drawable.no_internet_placeholder);
viewHolder.mCustomTextViewTitle.setText(R.string.connection_problem_title);
viewHolder.mCustomTextViewDescription.setText(R.string.connection_problem_description);
viewHolder.refreshText.setText(R.string.swipe);
//viewHolder.mCustomButton.setText(R.string.try_again);
viewHolder.mCustomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getMyPastBooking();
}
});
}
});
}
}
and activity_my_booking layout is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/layout_toolbar" />
<include layout="#layout/content_my_booking" />
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.SwipeRefreshLayout>
Set the first RecyclerView’s height to wrap_content and set setNestedScrollingEnabled to false
RecyclerView rv_ongoing_bookings= (RecyclerView) findViewById(R.id.rv_ongoing_bookings);
rv_ongoing_bookings.setNestedScrollingEnabled(false);
To achieve it my approach would be to customize my recyclerView adapter to act as a section header recycler view, something like this:
https://android-arsenal.com/details/1/4495
The following code will make recycler view expandable...
public class ExpandableRecyclerView extends RecyclerView
{
private boolean expanded = false;
public ExpandableRecyclerView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public ExpandableRecyclerView(Context context)
{
super(context);
}
public ExpandableRecyclerView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public boolean isExpanded()
{
return expanded;
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
if (isExpanded())
{
int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
else
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded)
{
this.expanded = expanded;
}
}
Usage... use it the way you use recycler view...
just set recyclerView.setExpanded(true);
You may directly use it inside scrollview...
So, it's not really an answer to your question, it's more like a suggestion to use RecyclerView as it should be depending on the screenshot which you included in your question.
You really don't need to create two RecyclerView's to achieve the layout which you need. As I understand you want to show some items and put a separator with text depending on something (Booking's date as I can see).
In RecyclerView.Adapter you have getItemViewType where you can return an int value depending on some variables.For example your getItemViewType should look something like this:
#Override
public int getItemViewType(int position) {
MyObject myObject = mItems.get(position);
// myObject.isSeparator() is a sample function which helps you identify it you should show construct a booking view or separator
if(myObject.isSeparator()){
// this variable is declared inside your Adapter ->
// private static final int VIEW_TYPE_SEPARATOR = 1;
return VIEW_TYPE_SEPARATOR;
}
// private static final int VIEW_TYPE_BOOKING = 0;
return VIEW_TYPE_BOOKING;
}
Depending on those values you need to create two ViewHolder's :
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (VIEW_TYPE_SEPARATOR == viewType) {
new SeparatorViewHolder(/* Some params which you need here */);
}
return new BookingViewHolder(/* Some other params which you need here */);
}
And ->
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (VIEW_TYPE_SEPARATOR == getItemViewType(position)) {
// Populate SeparatorViewHolder
} else {
// Populate BookingViewHolder
}
}
And at the end you should populate your List with the objects you need to determine if the item is a Booking item for example or a Separator.
I hope you got the main idea.
There is any way to add transculent dialog under toolbar in activity?
This is my layout:
<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.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?colorPrimary"
android:minHeight="?attr/actionBarSize"/>
<WebView
android:id="#+id/sa"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
and code for dialog:
public class TransparentProgressDialog extends DialogFragment {
private boolean mDialogCancelable = false;
private boolean mBackButtonPressed = false;
private OnDismissAfterBackPressed mOnDismissAfterBackPressed = null;
public static TransparentProgressDialog getInstance() {
TransparentProgressDialog transparentProgressDialog = new TransparentProgressDialog();
return transparentProgressDialog;
}
public static void dismiss(TransparentProgressDialog dialog) {
if (dialog != null) {
try {
dialog.dismissAllowingStateLoss();
} catch (Exception e) {
try {
dialog.dismiss();
} catch (Exception ex) {
Timber.e(ex, "TransparentProgressDialog dismiss");
}
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setCancelable(mDialogCancelable);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity(), android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.transparent_progress_bar);
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK) {
Timber.d("back button pressed");
mBackButtonPressed = true;
}
return false;
}
});
return dialog;
}
#Override
public void onStart() {
super.onStart();
Window window = getDialog().getWindow();
WindowManager.LayoutParams params = window.getAttributes();
params.dimAmount = 0.7f;
params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(params);
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (mDialogCancelable && mBackButtonPressed && mOnDismissAfterBackPressed != null) {
mOnDismissAfterBackPressed.backPressed();
}
}
public TransparentProgressDialog setCancelableDialog(boolean cancelable) {
this.mDialogCancelable = cancelable;
return this;
}
public TransparentProgressDialog setOnDismissAfterBackPressed(OnDismissAfterBackPressed onDismissAfterBackPressed) {
this.mOnDismissAfterBackPressed = onDismissAfterBackPressed;
return this;
}
public interface OnDismissAfterBackPressed {
void backPressed();
}
}
this dialog always is over my toolbar. How can I avoid that?
I am trying to implement to play youtube video in my app using youtubeplayer view when user clicks on button but its just playing for a millisecond,after that it just stop.App is not crashing but video is also not playing.
Code for the same is-
public class PlayVideo extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "xxxx";
String videoId;
String url="http://www.youtube.com/xxx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** attaching layout xml **/
setContentView(R.layout.activity_video_view);
/** Initializing YouTube player view **/
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubePlayerView.initialize(API_KEY, this);
videoId=getYoutubeVideoId(url);
Log.e("id",videoId);
//videoId=getIntent().getExtras().getString("url");
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.cueVideo(videoId);
}
}
private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
Log.e("on","buffer");
}
#Override
public void onPaused() {
Log.e("on","pause");
}
#Override
public void onPlaying() {
Log.e("on","play");
}
#Override
public void onSeekTo(int arg0) {
Log.e("on","seekto");
}
#Override
public void onStopped() {
Log.e("on","stop");
}
};
private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
#Override
public void onAdStarted() {
Log.e("on","ad");
}
#Override
public void onLoaded(String arg0) {
Log.e("on","loaded");
}
#Override
public void onLoading() {
Log.e("on","loading");
}
#Override
public void onVideoEnded() {
Log.e("on","vidEnd");
}
#Override
public void onVideoStarted() {
Log.e("on","vidStart");
}
#Override
public void onError(ErrorReason arg0) {
// TODO Auto-generated method stub
}
};
public static String getYoutubeVideoId(String youtubeUrl)
{
String video_id="";
if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http"))
{
String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches())
{
String groupIndex1 = matcher.group(7);
if(groupIndex1!=null && groupIndex1.length()==11)
video_id = groupIndex1;
}
}
return video_id;
}
}
xml file-
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.youtube.player.YouTubePlayerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="5dp" />
warning in logcat-
W/YouTubeAndroidPlayerAPI(8722): YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is not contained inside its ancestor com.google.android.youtube.player.YouTubePlayerView{41c88550 V.E..... ........ 0,0-480,270 #7f05003d app:id/youtube_player}. The distances between the ancestor's edges and that of the YouTubePlayerView is: left: -8, top: -8, right: -8, bottom: -8 (these should all be positive).
This issue is solved by using youtubeplayer fragment rather than youtubeplayer view.Code for the same is-
xml-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youtubeplayerfragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
java file-
public class PlayVideo extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
public static final String DEVELOPER_KEY = "your api key";
private static final int RECOVERY_DIALOG_REQUEST = 1;
String url="your video url";
String VIDEO_ID;
YouTubePlayerFragment myYouTubePlayerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_view);
myYouTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
myYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
VIDEO_ID=getYoutubeVideoId(url);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
"There was an error initializing the YouTubePlayer (%1$s)",
errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView)findViewById(R.id.youtubeplayerfragment);
}
public static String getYoutubeVideoId(String youtubeUrl)
{
String video_id="";
if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http"))
{
String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches())
{
String groupIndex1 = matcher.group(7);
if(groupIndex1!=null && groupIndex1.length()==11)
video_id = groupIndex1;
}
}
return video_id;
}
}
Add internet permission in your manifest file.