Scroll view move vertical on swipe the row horizontal - android

I have many customview in the scrollview. I have implemented swipe feature on the the customview . When I swipe customview to left , scrollview also move vertical. I don't want scroll view to be moved vertical while swiping. I thing Action_Cancel event of touch is going to scrollview which I have to stop. I tried to stop it but it is not working .
Below is the
package com.AA.KK.customui;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GestureDetectorCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.AA.ax4mobile.AAPreferences;
import com.AA.ax4mobile.Constants;
import com.AA.ax4mobile.Session;
import com.AA.ax4mobile.Utils;
import com.AA.ax4mobile.network.Network;
import com.AA.ax4mobile.network.NetworkResponseListener;
import com.AA.KK.R;
import com.AA.KK.activities.KKBaseActivity;
import com.AA.KK.activities.PDFViewerActivity;
public class MailLayout extends RelativeLayout implements OnClickListener, OnTouchListener,
GestureDetector.OnGestureListener {
private CheckBox checkBox;
private TextView title;
private TextView fileSize;
private ImageView fileIcon;
private ImageView tray;
private String url;
private String fileId;
private ViewGroup swipeView;
private boolean isPreview;
private boolean isSelected = true;
private GestureDetectorCompat mDetector;
private static final int SWIPE_OFFSET = 20;
private static final int ANIMATION_OFFSET= 30;
public MailLayout(Context context) {
super(context);
init(context);
// TODO Auto-generated constructor stub
}
#SuppressLint("NewApi")
private void init(Context context) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.activity_mail_layout, this);
LayoutParams linLayoutParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setLayoutParams(linLayoutParam);
swipeView = (RelativeLayout) findViewById(R.id.swipe);
swipeView.setOnTouchListener(this);
title = (TextView) findViewById(R.id.file_name);
fileIcon = (ImageView) findViewById(R.id.file_image);
fileSize = (TextView) findViewById(R.id.file_size);
tray = (ImageView) findViewById(R.id.clickme);
tray.setOnClickListener(this);
checkBox = (CheckBox) findViewById(R.id.chk_checkBox);
mDetector = new GestureDetectorCompat(Utils.getInstance().getContext(), this);
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
public boolean isPreview() {
return isPreview;
}
public void setPreview(boolean isPreview) {
this.isPreview = isPreview;
}
public ViewGroup getSwipeView() {
return swipeView;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public void setTitleText(String text) {
title.setText(text);
}
public String getTitleText() {
return (String) title.getText();
}
public void setFileSize(String text) {
fileSize.setText(text);
}
public void setChecked(boolean checked) {
checkBox.setChecked(checked);
}
public boolean getChecked() {
return checkBox.isChecked();
}
public void setFileIcon(String fileName) {
if (fileName.contains(".pdf") || fileName.contains(".PDF")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_pdf_selected);
} else if (fileName.contains(".docx") || fileName.contains(".DOCX")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_docx_selected);
} else if (fileName.contains(".doc") || fileName.contains(".DOC")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_doc_selected);
} else if (fileName.contains(".ppt") || fileName.contains(".PPT")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_ppt_selected);
} else if (fileName.contains(".pptx") || fileName.contains(".PPTX")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_pptx_selected);
} else if (fileName.contains(".png") || fileName.contains(".PNG")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_png_selected);
} else if (fileName.contains(".gif") || fileName.contains(".GIF")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_gif_selected);
} else if (fileName.contains(".csv") || fileName.contains(".CSV")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_csv_selected);
} else if (fileName.contains(".bmp") || fileName.contains(".BMP")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_bmp_selected);
} else if (fileName.contains(".txt") || fileName.contains(".TXT")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_txt_selected);
} else if (fileName.contains(".jpg") || fileName.contains(".jpeg") || fileName.contains(".JPG")
|| fileName.contains(".JPEG")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_jpg_selected);
} else if (fileName.contains(".xls") || fileName.contains(".XLS")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_xls_selected);
} else if (fileName.contains(".xlsx") || fileName.contains(".XLXS")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_xlsx_selected);
} else {
fileIcon.setBackgroundResource(R.drawable.ic_file_selected);
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener) {
checkBox.setOnCheckedChangeListener(listener);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.clickme:
doAddToTray(getFileId());
break;
}
}
public void setFileId(String fileId) {
this.fileId = fileId;
// TODO Auto-generated method stub
}
public String getFileId() {
return fileId;
}
public static void dismissProgress() {
Message msg = new Message();
msg.what = Constants.UIMSG_HIDE_PROGRESSDIALOG;
Bundle data = new Bundle();
data.putStringArray("caller", Utils.getInstance().getStackTraceArray());
msg.setData(data);
Session.getInstance().getMsgHandler().sendMessage(msg);
}
public static void showProgress() {
String message = Utils.getInstance().getContext().getString(R.string.loading);
Message msg = new Message();
msg.what = Constants.UIMSG_SHOW_PROGRESSDIALOG;
Bundle data = new Bundle();
data.putString("message", message);
data.putStringArray("caller", Utils.getInstance().getStackTraceArray());
msg.setData(data);
Session.getInstance().getMsgHandler().sendMessage(msg);
}
public static void doAddToTray(final String ids) {
AAPreferences settings = AAPreferences.getPreferences(Utils.getInstance().getContext());
String accToken = settings.getString(Constants.REQUEST_KEY_ACCESS_TOKEN, null);
String servername = settings.getString(Constants.REQUEST_KEY_SERVERNAME, null);
JSONObject req = new JSONObject();
Network net = Network.getInstance();
try {
req.accumulate(Constants.REQUEST_KEY_ACCESS_TOKEN, accToken);
req.accumulate(Constants.REQUEST_KEY_SERVERNAME, servername);
req.accumulate(Constants.REQUEST_KEY_ID, ids);
req.accumulate(Constants.REQUEST_KEY_PARENT_ID, "");
showProgress();
NetworkResponseListener listener = new NetworkResponseListener() {
#Override
public void handleSuccessResponse(List<NameValuePair> request, JSONObject response, boolean cancelflag) {
dismissProgress();
Toast.makeText(Utils.getInstance().getContext(), R.string.file_added_to_move_tray,
Toast.LENGTH_LONG).show();
String count = null;
try {
JSONObject json = response.getJSONObject("payload");
count = json.getString("total_count");
if (!TextUtils.isEmpty(count))
Utils.getInstance().saveTrayCount(count);
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(Constants.ACTION_UPDATE_TRAY);
LocalBroadcastManager.getInstance(Utils.getInstance().getContext()).sendBroadcast(intent);
}
#Override
public void handleErrorResponse(List<NameValuePair> request, JSONObject response, boolean cancelflag) {
dismissProgress();
String count = null;
try {
JSONObject json = response.getJSONObject("payload");
count = json.getString("total_count");
Utils.getInstance().saveTrayCount(count);
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(Constants.ACTION_UPDATE_TRAY);
LocalBroadcastManager.getInstance(Utils.getInstance().getContext()).sendBroadcast(intent);
Message msg = Network.defaultErrorManager(request, response);
if (msg != null) {
KKBaseActivity.defaultUIHandler.sendMessage(msg);
}
}
};
net.linkTray(req, listener);
} catch (JSONException e) {
e.printStackTrace();
}
};
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// TODO Auto-generated method stub
Log.e("onFling", "event"+e1.getAction());
if (swipeView.getX() > -(tray.getWidth() + SWIPE_OFFSET)) {
swipeView.animate().translationX(0).alpha(1).setDuration(ANIMATION_OFFSET).setListener(null);
} else {
if (isPreview) {
swipeView.animate().translationX(0).alpha(1).setDuration(ANIMATION_OFFSET).setListener(null);
} else {
swipeView.animate().translationX(-(tray.getWidth() + SWIPE_OFFSET)).alpha(1).setDuration(ANIMATION_OFFSET).setListener(null);
}
}
return false;
}
#Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// TODO Auto-generated method stub
if (isSelected) {
if (swipeView.getX() <= 0)
swipeView.setX(e2.getX() - e1.getX() + swipeView.getX());
}
return true;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
String s = getUrl();
if (getUrl() == "" || getUrl() == null || getUrl().equalsIgnoreCase("null")) {
Toast.makeText(Utils.getInstance().getContext(), "File is not viewable", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(Utils.getInstance().getContext(), PDFViewerActivity.class);
intent.putExtra("filename", getTitleText());
intent.putExtra("view_url", getUrl());
intent.putExtra("preview_from_notification", true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Utils.getInstance().getContext().startActivity(intent);
}
return true;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Log.e("onTouch", "event"+event.getAction());
boolean flag;
if (isPreview) {
tray.setVisibility(View.INVISIBLE);
} else {
tray.setVisibility(View.VISIBLE);
}
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
flag = onFling(event, event, 0f, 0f);
} else {
flag = mDetector.onTouchEvent(event);
}
return flag;
}
/* #Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
Log.e("onTouchEvent", "event"+event.getAction());
return super.onTouchEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev){
Log.e("dispatchTouchEvent", "event"+ev.getAction());
if(ev.getAction()== 3)
return false;
else
return super.dispatchTouchEvent(ev);
}*/
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
Log.e("onInterceptTouchEvent", "event"+ev.getAction());
return true;
}
}

in your onScroll()
put this -
ViewParent parent = getParent();
if(parent!= null){
parent.requestDisallowOnInterceptTouchEvent(true);
}

Related

'Google Now' Voice Search in Android App

I'm not even sure if this is the right thing to do any more with Google not supporting 'Google Now', but I can't seem to find any suitable alternative.
Using this https://antonioleiva.com/voice_search_google_now/#comment-8611 as a guide I am trying o implement a voice search in my App, but not having much luck.
I already have a search facility for users. What I have done so far:-
GlobalApplication.java
public static Queries getQueriesInstance(Context context) {
if(q == null) {
dbHelper = new DbHelper(context);
q = new Queries(db, dbHelper);
}
return q;
}
Then in MainActivity.java
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Intent i;
int id = item.getItemId();
...
...
if(id == R.id.nav_search) {
i = new Intent(this, SearchActivity.class);
startActivity(i);
}
...
...
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
And finally, before adding anything, my SearchActivity.java file
package com.projects.activities;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.SpannableString;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.application.GlobalApplication;
import com.config.Config;
import com.db.Queries;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.libraries.asynctask.MGAsyncTaskNoDialog;
import com.libraries.dataparser.DataParser;
import com.libraries.location.MGLocationManagerUtils;
import com.libraries.utilities.MGUtilities;
import com.models.DataResponse;
import com.models.Deal;
import com.models.DealCategory;
import com.models.Status;
import com.projects.adapp.R;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class SearchActivity extends AppCompatActivity implements
GlobalApplication.OnLocationListener{
private AsyncTaskNoDialog task;
SeekBar seekBarRadius;
SwipeRefreshLayout swipeRefresh;
Queries q;
Button btnSearch;
ArrayList<DealCategory> selectedCategories;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
setContentView(R.layout.activity_list_swipe_search);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.search);
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefresh.setClickable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
swipeRefresh.setProgressViewOffset(false, 0,100);
}
swipeRefresh.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
showRefresh(false);
q = GlobalApplication.getQueriesInstance(this);
seekBarRadius = (SeekBar) findViewById(R.id.seekBarRadius);
seekBarRadius.setMax(Config.SEARCH_RADIUS_MAX_VALUE);
seekBarRadius.setProgress(Config.SEARCH_RADIUS_DEFAULT_VALUE);
seekBarRadius.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) { }
#Override
public void onStartTrackingTouch(SeekBar arg0) { }
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
updateRadius(progress);
}
});
updateRadius(seekBarRadius.getProgress());
selectedCategories = new ArrayList<DealCategory>();
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
search();
}
});
FrameLayout frameCategory = (FrameLayout) findViewById(R.id.frameCategory);
frameCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SearchActivity.this, CategorySearchActivity.class);
startActivityForResult(i, Config.RESULT_CODE_CATEGORY);
}
});
seekBarRadius.setEnabled(false);
btnSearch.setEnabled(false);
if(!MGUtilities.isLocationEnabled(this) && GlobalApplication.currentLocation == null) {
MGLocationManagerUtils utils = new MGLocationManagerUtils();
utils.setOnAlertListener(new MGLocationManagerUtils.OnAlertListener() {
#Override
public void onPositiveTapped() {
startActivityForResult(
new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS),
Config.PERMISSION_REQUEST_LOCATION_SETTINGS);
}
#Override
public void onNegativeTapped() {
Toast.makeText(SearchActivity.this, R.string.location_error_not_turned_on_search, Toast.LENGTH_LONG).show();
}
});
utils.showAlertView(
this,
R.string.location_error,
R.string.gps_not_on,
R.string.go_to_settings,
R.string.cancel);
}
else {
refetch();
}
GlobalApplication app = (GlobalApplication)getApplication();
app.sendScreenView(Config.kGAIScreenNameSearch);
}
public void refetch() {
GlobalApplication app = (GlobalApplication) getApplication();
app.setOnLocationListener(this, this);
}
#Override
public void onLocationChanged(Location prevLoc, Location currentLoc) {
GlobalApplication app = (GlobalApplication) getApplication();
app.setOnLocationListener(null, this);
seekBarRadius.setEnabled(true);
btnSearch.setEnabled(true);
}
#Override
public void onLocationRequestDenied() {
MGUtilities.showAlertView(this, R.string.permission_error, R.string.permission_error_details_location);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Config.RESULT_CODE_CATEGORY && resultCode == RESULT_OK) {
selectedCategories = (ArrayList<DealCategory>) data.getSerializableExtra("categories");
if(selectedCategories != null && selectedCategories.size() > 0) {
TextView tvCategory = (TextView) findViewById(R.id.tvCategory);
String cats = "";
for(int x = 0; x < selectedCategories.size(); x++) {
DealCategory cat = selectedCategories.get(x);
cats += cat.getCategory();
if(x < selectedCategories.size() - 1)
cats += ", ";
}
if(!cats.isEmpty()) {
tvCategory.setText(cats);
}
else {
tvCategory.setText(R.string.all_categories);
}
}
}
if (requestCode == Config.PERMISSION_REQUEST_LOCATION_SETTINGS) {
if(MGUtilities.isLocationEnabled(this))
refetch();
else {
Toast.makeText(this, R.string.location_error_not_turned_on_search, Toast.LENGTH_LONG).show();
}
}
}
public void updateRadius(int progress){
String strSeekVal = String.format("%d %s",
progress,
MGUtilities.getStringFromResource(SearchActivity.this, R.string.km));
TextView tvRadius = (TextView) findViewById(R.id.tvRadius);
tvRadius.setText(strSeekVal);
}
public void showRefresh(boolean show) {
swipeRefresh.setRefreshing(show);
swipeRefresh.setEnabled(show);
}
public void search() {
showRefresh(true);
beginParsing();
}
public ArrayList<Deal> searchLocal() {
EditText txtSearch = (EditText) findViewById(R.id.txtSearch);
String filterSearch = Html.toHtml(new SpannableString(txtSearch.getText().toString()));
String searchStr = MGUtilities.filterInvalidChars(filterSearch);
int radius = seekBarRadius.getProgress();
int countParams = 0;
countParams += searchStr.length() > 0 ? 1 : 0;
countParams += radius > 0 ? 1 : 0;
countParams += selectedCategories != null && selectedCategories.size() > 0 ? 1 : 0;
ArrayList<Deal> array = q.getDeals();
ArrayList<Deal> results = new ArrayList<>();
for(Deal event : array) {
try {
int qualifyCount = 0;
if(searchStr.length() > 0) {
boolean isFound = searchStr.contains(event.getTitle()) ||
searchStr.contains(event.getAddress()) ||
searchStr.contains(event.getDesc()) ||
event.getTitle().contains(searchStr) ||
event.getAddress().contains(searchStr) ||
event.getDesc().contains(searchStr);
if(isFound)
qualifyCount += 1;
}
if(GlobalApplication.currentLocation != null) {
Location loc1 = new Location("Loc1");
loc1.setLatitude(event.getLat());
loc1.setLongitude(event.getLon());
Location loc2 = new Location("Loc2");
loc2.setLatitude(GlobalApplication.currentLocation.getLatitude());
loc2.setLongitude(GlobalApplication.currentLocation.getLongitude());
double distance = loc1.distanceTo(loc2) * Config.METERS_TO_KM;
event.setDistance(distance);
if(distance <= radius)
qualifyCount += 1;
}
ObjectMapper mapper = new ObjectMapper();
DataResponse categories = mapper.readValue(event.getCategories(), DataResponse.class);
if(categories != null && categories.getCategories() != null) {
for(DealCategory cat : categories.getCategories()) {
boolean isFound = false;
for(DealCategory selectedCat : selectedCategories) {
if(selectedCat.getCategory_id() == cat.getCategory_id()) {
isFound = true;
break;
}
}
if(isFound) {
qualifyCount += 1;
break;
}
}
}
if(qualifyCount == countParams)
results.add(event);
}
catch(Exception e) {
e.printStackTrace();
}
}
return results;
}
public void beginParsing() {
if(task != null)
task.cancel(true);
task = new MGAsyncTaskNoDialog(this);
task.setMGAsyncTaskListener(new MGAsyncTaskNoDialog.OnMGAsyncTaskListenerNoDialog() {
DataResponse response;
ArrayList<Deal> events;
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTaskNoDialog asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTaskNoDialog asyncTask) { }
#Override
public void onAsyncTaskPostExecute(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
updateData(response, events);
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
if(MGUtilities.hasConnection(SearchActivity.this)) {
response = syncData();
}
else{
events = searchLocal();
}
}
});
task.execute();
}
public DataResponse syncData() {
String cats = "";
for(int x = 0; x < selectedCategories.size(); x++) {
DealCategory cat = selectedCategories.get(x);
cats += String.valueOf(cat.getCategory_id());
if (x < selectedCategories.size() - 1)
cats += ",";
}
EditText txtSearch = (EditText) findViewById(R.id.txtSearch);
String filterSearch = Html.toHtml(new SpannableString(txtSearch.getText().toString()));
String searchStr = MGUtilities.filterInvalidChars(filterSearch);
double radius = seekBarRadius.getProgress() * Config.KM_TO_MILES;
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("keywords", searchStr ));
params.add(new BasicNameValuePair("lat", String.valueOf(GlobalApplication.currentLocation.getLatitude()) ));
params.add(new BasicNameValuePair("lon", String.valueOf(GlobalApplication.currentLocation.getLongitude()) ));
params.add(new BasicNameValuePair("category_ids", cats) );
params.add(new BasicNameValuePair("radius", String.valueOf(radius)) );
params.add(new BasicNameValuePair("api_key", Config.API_KEY ));
GlobalApplication.params = params;
DataResponse response = DataParser.getJSONFromUrlWithPostRequest(Config.SEARCH_DEALS_JSON_URL, params);
return response;
}
public void updateData(DataResponse response, ArrayList<Deal> deals) {
showRefresh(false);
if(response != null) {
Status status = response.getStatus();
if(status.getStatus_code() == -1 && response.getDeals() != null ) {
if(response.getDeals().size() == 0) {
Toast.makeText(SearchActivity.this, R.string.no_results_found, Toast.LENGTH_SHORT).show();
return;
}
Intent i = new Intent(this, SearchResultsActivity.class);
i.putExtra("deals", response.getDeals());
startActivity(i);
}
else {
MGUtilities.showAlertView(this, R.string.network_error, status.getStatus_text());
}
}
else if(deals != null && deals.size() > 0) {
GlobalApplication.params = null;
Intent i = new Intent(this, SearchResultsActivity.class);
i.putExtra("deals", deals);
startActivity(i);
}
else {
MGUtilities.showAlertView(this, R.string.network_error, R.string.problems_encountered_while_syncing);
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
// Handle action bar actions click
switch (item.getItemId()) {
default:
finish();
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(android.view.Menu menu) {
// if nav drawer is opened, hide the action items
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onDestroy() {
super.onDestroy();
if(task != null)
task.cancel(true);
}
}
Taken from the tutorial link above, I then added the following to my Manifest
AndroidManifest.xml
<activity
android:name="com.projects.activities.SearchActivity">
<intent-filter>
<action android:name="com.google.android.gms.actions.SEARCH_ACTION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
I then added the following to my SearchActivity.java file
private static final String ACTION_VOICE_SEARCH =
"com.google.android.gms.actions.SEARCH_ACTION";
private void handleVoiceSearch(Intent intent) {
if (intent != null && ACTION_VOICE_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
setSearchViewVisible(true);
searchView.setQuery(query, true);
}
}
The in various places and in slightly different ways, I have tried adding
handleVoiceSearch(getIntent());
to the SearchActivity.java file, but I don't seem to be having much luck. I am testing from an Alpha version uploaded to Play Store.
Is there anything obvious anyone can see I am missing?
Thanks

Clear Cache of All Apps in Marshmallow?

I try to solve using below code:
[Reference: Android: Clear Cache of All Apps?
PackageManager pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
// Found the method I want to use
try {
long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
m.invoke(pm, desiredFreeStorage , null);
} catch (Exception e) {
// Method invocation failed. Could be a permission problem
}
break;
}
}
and add permission in AndroidMenifest.xml file
<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>
But when i run this code, then throw exception :
java.lang.IllegalArgumentException: Wrong number of arguments; expected 3, got 2
Any suggestion to overcome this exception or another solution for clear cache of all apps programmatically. Thanks
follow the link. hopefully get a solutions
https://fossdroid.com/s.html?q=cache+cleaner
import android.Manifest;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SearchView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;
import com.frozendevs.cache.cleaner.R;
import com.frozendevs.cache.cleaner.activity.SettingsActivity;
import com.frozendevs.cache.cleaner.model.AppsListItem;
import com.frozendevs.cache.cleaner.model.CleanerService;
import com.frozendevs.cache.cleaner.model.adapter.AppsListAdapter;
import com.frozendevs.cache.cleaner.widget.DividerDecoration;
import com.frozendevs.cache.cleaner.widget.RecyclerView;
import java.util.List;
public class CleanerFragment extends Fragment implements CleanerService.OnActionListener {
private static final int REQUEST_STORAGE = 0;
private static final String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private CleanerService mCleanerService;
private AppsListAdapter mAppsListAdapter;
private TextView mEmptyView;
private SharedPreferences mSharedPreferences;
private ProgressDialog mProgressDialog;
private View mProgressBar;
private TextView mProgressBarText;
private LinearLayoutManager mLayoutManager;
private Menu mOptionsMenu;
private boolean mAlreadyScanned = false;
private boolean mAlreadyCleaned = false;
private String mSearchQuery;
private String mSortByKey;
private String mCleanOnAppStartupKey;
private String mExitAfterCleanKey;
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mCleanerService = ((CleanerService.CleanerServiceBinder) service).getService();
mCleanerService.setOnActionListener(CleanerFragment.this);
updateStorageUsage();
if (!mCleanerService.isCleaning() && !mCleanerService.isScanning()) {
if (mSharedPreferences.getBoolean(mCleanOnAppStartupKey, false) &&
!mAlreadyCleaned) {
mAlreadyCleaned = true;
cleanCache();
} else if (!mAlreadyScanned) {
mCleanerService.scanCache();
}
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
mCleanerService.setOnActionListener(null);
mCleanerService = null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
mSortByKey = getString(R.string.sort_by_key);
mCleanOnAppStartupKey = getString(R.string.clean_on_app_startup_key);
mExitAfterCleanKey = getString(R.string.exit_after_clean_key);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mAppsListAdapter = new AppsListAdapter();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setTitle(R.string.cleaning_cache);
mProgressDialog.setMessage(getString(R.string.cleaning_in_progress));
mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
return true;
}
});
getActivity().getApplication().bindService(new Intent(getActivity(), CleanerService.class),
mServiceConnection, Context.BIND_AUTO_CREATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.cleaner_fragment, container, false);
mEmptyView = (TextView) rootView.findViewById(R.id.empty_view);
mLayoutManager = new LinearLayoutManager(getActivity());
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAppsListAdapter);
recyclerView.setEmptyView(mEmptyView);
recyclerView.addItemDecoration(new DividerDecoration(getActivity()));
mProgressBar = rootView.findViewById(R.id.progressBar);
mProgressBarText = (TextView) rootView.findViewById(R.id.progressBarText);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
mOptionsMenu = menu;
inflater.inflate(R.menu.main_menu, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
mSearchQuery = query;
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (ViewCompat.isLaidOut(searchView) && mSearchQuery != null) {
String oldText = mSearchQuery;
mSearchQuery = newText;
if (!oldText.equals(newText)) {
mAppsListAdapter.sortAndFilter(getActivity(), getSortBy(), newText);
}
}
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchItem,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
if (mSearchQuery == null) {
mSearchQuery = "";
}
mAppsListAdapter.setShowHeaderView(false);
mEmptyView.setText(R.string.no_such_app);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
mSearchQuery = null;
mAppsListAdapter.clearFilter();
mAppsListAdapter.setShowHeaderView(true);
if (mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
mLayoutManager.scrollToPosition(0);
}
mEmptyView.setText(R.string.empty_cache);
return true;
}
});
if (mSearchQuery != null) {
MenuItemCompat.expandActionView(searchItem);
searchView.setQuery(mSearchQuery, false);
}
updateOptionsMenu();
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_clean:
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning() && mCleanerService.getCacheSize() > 0) {
mAlreadyCleaned = false;
cleanCache();
}
return true;
case R.id.action_refresh:
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning()) {
mCleanerService.scanCache();
}
return true;
case R.id.action_settings:
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
case R.id.action_sort_by_app_name:
setSortBy(AppsListAdapter.SortBy.APP_NAME);
updateOptionsMenu();
return true;
case R.id.action_sort_by_cache_size:
setSortBy(AppsListAdapter.SortBy.CACHE_SIZE);
updateOptionsMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
updateOptionsMenu();
}
#Override
public void onDestroyOptionsMenu() {
mOptionsMenu = null;
}
#Override
public void onResume() {
updateStorageUsage();
updateOptionsMenu();
if (mCleanerService != null) {
if (mCleanerService.isScanning() && !isProgressBarVisible()) {
showProgressBar(true);
} else if (!mCleanerService.isScanning() && isProgressBarVisible()) {
showProgressBar(false);
}
if (mCleanerService.isCleaning() && !mProgressDialog.isShowing()) {
mProgressDialog.show();
}
}
super.onResume();
}
#Override
public void onPause() {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
super.onPause();
}
#Override
public void onDestroy() {
getActivity().getApplication().unbindService(mServiceConnection);
super.onDestroy();
}
private void updateOptionsMenu() {
if (mOptionsMenu != null) {
mOptionsMenu.findItem(R.id.action_sort_by_app_name).setVisible(
getSortBy() == AppsListAdapter.SortBy.CACHE_SIZE);
mOptionsMenu.findItem(R.id.action_sort_by_cache_size).setVisible(
getSortBy() == AppsListAdapter.SortBy.APP_NAME);
}
}
private void updateStorageUsage() {
if (mAppsListAdapter != null) {
StatFs stat = new StatFs(Environment.getDataDirectory().getAbsolutePath());
long totalMemory = (long) stat.getBlockCount() * (long) stat.getBlockSize();
long medMemory = mCleanerService != null ? mCleanerService.getCacheSize() : 0;
long lowMemory = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB &&
!Environment.isExternalStorageEmulated()) {
stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
totalMemory += (long) stat.getBlockCount() * (long) stat.getBlockSize();
lowMemory += (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
}
long highMemory = totalMemory - medMemory - lowMemory;
mAppsListAdapter.updateStorageUsage(totalMemory, lowMemory, medMemory, highMemory);
}
}
private AppsListAdapter.SortBy getSortBy() {
try {
return AppsListAdapter.SortBy.valueOf(mSharedPreferences.getString(mSortByKey,
AppsListAdapter.SortBy.CACHE_SIZE.toString()));
} catch (ClassCastException e) {
return AppsListAdapter.SortBy.CACHE_SIZE;
}
}
private void setSortBy(AppsListAdapter.SortBy sortBy) {
mSharedPreferences.edit().putString(mSortByKey, sortBy.toString()).apply();
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning()) {
mAppsListAdapter.sortAndFilter(getActivity(), sortBy, mSearchQuery);
}
}
private boolean isProgressBarVisible() {
return mProgressBar.getVisibility() == View.VISIBLE;
}
private void showProgressBar(boolean show) {
if (show) {
mProgressBar.setVisibility(View.VISIBLE);
} else {
mProgressBar.startAnimation(AnimationUtils.loadAnimation(
getActivity(), android.R.anim.fade_out));
mProgressBar.setVisibility(View.GONE);
}
}
private void showStorageRationale() {
AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
dialog.setTitle(R.string.rationale_title);
dialog.setMessage(getString(R.string.rationale_storage));
dialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
private void cleanCache() {
if (!CleanerService.canCleanExternalCache(getActivity())) {
if (shouldShowRequestPermissionRationale(PERMISSIONS_STORAGE[0])) {
showStorageRationale();
} else {
requestPermissions(PERMISSIONS_STORAGE, REQUEST_STORAGE);
}
} else {
mCleanerService.cleanCache();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_STORAGE) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mCleanerService.cleanCache();
} else {
showStorageRationale();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onScanStarted(Context context) {
if (isAdded()) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
mProgressBarText.setText(R.string.scanning);
showProgressBar(true);
}
}
#Override
public void onScanProgressUpdated(Context context, int current, int max) {
if (isAdded()) {
mProgressBarText.setText(getString(R.string.scanning_m_of_n, current, max));
}
}
#Override
public void onScanCompleted(Context context, List<AppsListItem> apps) {
mAppsListAdapter.setItems(getActivity(), apps, getSortBy(), mSearchQuery);
if (isAdded()) {
updateStorageUsage();
showProgressBar(false);
}
mAlreadyScanned = true;
}
#Override
public void onCleanStarted(Context context) {
if (isAdded()) {
if (isProgressBarVisible()) {
showProgressBar(false);
}
if (!getActivity().isFinishing()) {
mProgressDialog.show();
}
}
}
#Override
public void onCleanCompleted(Context context, boolean succeeded) {
if (succeeded) {
mAppsListAdapter.trashItems();
}
if (isAdded()) {
updateStorageUsage();
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
Toast.makeText(context, succeeded ? R.string.cleaned : R.string.toast_could_not_clean,
Toast.LENGTH_LONG).show();
if (succeeded && getActivity() != null && !mAlreadyCleaned &&
mSharedPreferences.getBoolean(mExitAfterCleanKey, false)) {
getActivity().finish();
}
}
}
It looks like there is an additional freeStorage() method added in Android 6 (Marshmallow) that takes an additional volumeUuid parameter:
public void freeStorage(long freeStorageSize, IntentSender pi)
public abstract void freeStorage(String volumeUuid, long freeStorageSize,
IntentSender pi)
Obviously, the new method is showing up first in the returned list of declared methods.
To get around this, you can alter the orginal code so that it looks like this:
PackageManager pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
Class[] params = m.getParameterTypes();
if (params.length == 2) {
// Found the method I want to use
try {
long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
m.invoke(pm, desiredFreeStorage , null);
} catch (Exception e) {
// Method invocation failed. Could be a permission problem
}
break;
}
}
}

Create custom WebView Cordova Android 5.1.0

I need to create 3 custom Cordova WebView using Cordova Android 5.1.0. Previously I have succeeded to create custom WebView using Cordova Android 2.7 by modifying/overwriting file platform/android/src/com/hello/helloapp.java. Below is my previous code:
package com.hello.helloapp;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewClient;
import com.hello.helloapp.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class HelloApp extends Activity implements CordovaInterface {
int SCREEN_WIDTH;
int SCREEN_HEIGHT;
static String parentUrl;;
CordovaWebView view2;
CordovaWebView view1;
CordovaWebView view3;
static String htmlStr;
LinearLayout layout;
boolean connectionStatus;
private final ExecutorService threadPool = Executors.newCachedThreadPool();
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Config.init(this);
this.getScreenSize();
view1 = (CordovaWebView) findViewById(R.id.local_web_view);
view1.loadUrl("file:///android_asset/www/index.html");
view2 = (CordovaWebView) findViewById(R.id.external_web_view);
view2.loadUrl("http://google.com");
view2.requestFocus(WebView.FOCUS_DOWN);
view2.setWebViewClient(new MyWebViewClient(this, view2));
view3 = (CordovaWebView) findViewById(R.id.articles_web_view);
view3.loadUrl("file:///android_asset/www/articles.html");
view2.addJavascriptInterface(this, "GetHTML");
layout = (LinearLayout) findViewById(R.id.progressBar);
if (!isTabletDevice(this)) {
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
if (isAirplaneModeOn(this)) {
connectionStatus = false;
} else if (isNetworkOnline()) {
connectionStatus = true;
} else
connectionStatus = false;
System.out.println(connectionStatus);
if (!connectionStatus) {
view2.setVisibility(View.GONE);
view3.loadUrl("file:///android_asset/www/articles.html");
view3.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isNetworkOnline() {
boolean status = false;
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
NetworkInfo netInfo1 = cm.getNetworkInfo(1);
if ((netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED)
|| (netInfo1 != null && netInfo1.getState() == NetworkInfo.State.CONNECTED)) {
status = true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
System.out.println(status);
return status;
}
public static boolean isTabletDevice(Context activityContext) {
// Verifies if the Generalized Size of the device is XLARGE to be
// considered a Tablet
boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
// If XLarge, checks if the Generalized Density is at least MDPI
// (160dpi)
if (xlarge) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
// DENSITY_TV=213, DENSITY_XHIGH=320
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
// Yes, this is a tablet!
return true;
}
}
// No, this is not a tablet!
return false;
}
#SuppressWarnings("deprecation")
private static boolean isAirplaneModeOn(Context context)
throws SettingNotFoundException {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
#Override
public Activity getActivity() {
return this;
}
#Override
public ExecutorService getThreadPool() {
return threadPool;
}
public void getScreenSize() {
Display display = getWindowManager().getDefaultDisplay();
SCREEN_WIDTH = display.getWidth();
SCREEN_HEIGHT = display.getHeight();
}
public class MyWebViewClient extends CordovaWebViewClient {
private CordovaInterface cordova;
public MyWebViewClient(CordovaInterface ctx, CordovaWebView app) {
super(ctx, app);
this.cordova = ctx;
}
#Override
public void onReceivedError(WebView arg0, int arg1, String arg2,
String arg3) {
arg0.loadUrl("javascript:navigator.notification.alert(\"Sorry,the network is not available.\",\"null\");");
}
public boolean shouldOverrideUrlLoading(final WebView view, String url) {
connectionStatus = isNetworkOnline();
System.out.println(connectionStatus);
if (connectionStatus) {
System.out.println("---------shouldoverride-------" + url);
if (url.contains(".pdf")&& !url.contains("originUrl")) {
System.out.println(HelloApp.htmlStr);
view1.loadUrl("javascript:downloadFile(\"" + url + "\",\""
+ HelloApp.htmlStr + "\",\"" + HelloApp.parentUrl
+ "\");");
return false;
} else if (url.contains("search?")
&& HelloApp.parentUrl
.equalsIgnoreCase("http://google.com/")) {
System.out.println("parenturl");
url = url.concat("&showAll=false");
view2.loadUrl(url);
return false;
} else {
return false;
}
} else {
view1.loadUrl("javascript:navigator.notification.alert(\"Sorry,the network is not available.\",\"null\");");
return true;
}
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layout.setVisibility(View.VISIBLE);
if (url.contains(".pdf")) {
}else {
HelloApp.parentUrl = url;
if (view2.canGoBack() && view2.canGoForward()) {
view1.loadUrl("javascript:callBackFun(\"F_1B_1\")");
} else if (view2.canGoForward()) {
view1.loadUrl("javascript:callBackFun(\"F_1\")");
} else if (view2.canGoBack()) {
view1.loadUrl("javascript:callBackFun(\"B_1\")");
}
}
super.onPageStarted(view, url, favicon);
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains(".pdf")) {
} else {
System.out.println("----------------" + url);
view2.loadUrl("javascript: GetHTML.getHtml(document.body.innerHTML);");
view2.loadUrl("javascript: $(\".content-pricing\").hide()");
view2.loadUrl("javascript: $(\"a[href*='mailto']\").removeAttr('href');");
System.out.println("REMOVE------------------------>>>");
view2.loadUrl("javascript:$('head').append('<style>#coverImageUrl, .content-pricing, .price-disclaimer {display : none;}</style>')");
layout.setVisibility(View.INVISIBLE);
}
}
}
public Object onMessage(String arg0, Object arg1) {
return null;
}
#Override
public void setActivityResultCallback(CordovaPlugin arg0) {
}
#Override
public void startActivityForResult(CordovaPlugin arg0, Intent arg1, int arg2) {
}
#JavascriptInterface
public void getHtml(String html) {
this.htmlStr = html.replace("\"", "\'").replaceAll("\n", "").replaceAll("%22", "\'").trim();
}
}
Now there is lots of update in Cordova, they also update there CordovaWebView code. After updating Cordova Android version from 2.7 to 5.1.0, app is crashed. I tried to use SystemWebView instead of CordovaWebView but still get error and crashes as some of methods are missing in SystemWebView.
Please help how can I update previous WebView code or create new multiple WebView in Cordova 5.1.0.
Thanks!!
This is how I implemented new Cordova library in my existing project.
public class MyWebViewFragment extends Fragment{
private Activity mActivity;
private SystemWebView syswvPhoneWebview;
private CordovaWebView wvPhoneWebview;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (Activity) context;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (mView == null) {
mView = inflater.inflate(R.layout.fragment_web_view, null);
setLayoutViews(mView);
}
return mView;
}
private void setLayoutViews(View mView) {
syswvPhoneWebview = (SystemWebView) mView.findViewById(R.id.wvPhoneWebview);
wvPhoneWebview = new CordovaWebViewImpl(new SystemWebViewEngine(syswvPhoneWebview));
wvPhoneWebview.init((CordovaInterface) getParentFragment(), parser.getPluginEntries(), parser.getPreferences());
syswvPhoneWebview.setWebContentsDebuggingEnabled(true);
syswvPhoneWebview.getSettings().setLoadsImagesAutomatically(true);
syswvPhoneWebview.getSettings().setJavaScriptEnabled(true);
syswvPhoneWebview.getSettings().setDomStorageEnabled(true);
syswvPhoneWebview.getSettings().setBuiltInZoomControls(true);
syswvPhoneWebview.getSettings().setSupportZoom(true);
wvPhoneWebview.loadUrl("www.google.com");
SystemWebViewEngine systemWebViewEngine = (SystemWebViewEngine) wvPhoneWebview.getEngine();
syswvPhoneWebview.setWebViewClient(new DocumentViewClient(systemWebViewEngine, mActivity));
}
}
now webviewclient code.
public class DocumentViewClient extends SystemWebViewClient {
private final Activity activity;
public DocumentViewClient(SystemWebViewEngine parentEngine, Activity activity) {
super(parentEngine);
this.activity = activity;
}
}

why onInterceptTouchEvent overrides the all touch event

I have a viewpager and several fragments.I extend a ViewPager and implement a my own class.Also i implemented onInterceptTouchEvent method.Now when i swipe it doesn't work.I think onInterceptTouchEvent intercept them. How to handle this?
package com.android.ho;
import com.sph.custom.ViewPagerWithTapGestreDetection;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class PDFActivity extends FragmentActivity implements ImageOnTapCallback,OnPageChangeListener{
static final int ITEMS = 20;
MyAdapter mAdapter;
//ViewPager mPager;
ViewPagerWithTapGestreDetection mPager;
//ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
try {
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPagerWithTapGestreDetection) findViewById(R.id.pager);
mPager.setId(5000);
mPager.setImageOnTapCallback(this);
mPager.setAdapter(mAdapter);
//mPager.setOffscreenPageLimit(1);
mPager.setOnPageChangeListener(this);
/*
Button button = (Button) findViewById(R.id.first);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.last);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(ITEMS - 1);
}
});
*/
mPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show image
return MyFragment.newInstance("1.pdf");
case 1: // Fragment # 1 - This will show image
return MyFragment.newInstance("2.pdf");
case 2: // Fragment # 1 - This will show image
return MyFragment.newInstance("3.pdf");
case 3: // Fragment # 1 - This will show image
return MyFragment.newInstance("4.pdf");
case 4: // Fragment # 1 - This will show image
return MyFragment.newInstance("5.pdf");
default:// Fragment # 2-9 - Will show list
return MyFragment.newInstance("1.pdf");
}
}
}
#Override
public void tapDetected() {
// TODO Auto-generated method stub
Log.e("tapDetected", "tapDetected");
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageScrollStateChanged", "onPageScrollStateChanged");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
Log.e("onPageScrolled", "onPageScrolled");
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageSelected", "onPageSelected");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("onDestroy", "onDestroy onDestroy onDestroy");
}
}
This is my fragment class
package com.android.ho;
import java.io.File;
import java.io.InputStream;
import com.epapyrus.plugpdf.core.viewer.ReaderView;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MyFragment extends Fragment{
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static int count = 1;
static String file;
TextView txt;
ReaderView readerView;
public static final MyFragment newInstance(String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
file = message;
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
try {
File fl = new File(Environment.getExternalStorageDirectory(), "/pdf/2.pdf");
readerView = (ReaderView) v.findViewById(R.id.pdfviews);
//readerView.setOnClickListener(this);
Log.e("readerView", fl.toString());
v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return true;
}
});
// readerView.openFile("/mnt/sdcard/pdf/1.pdf","");
if (count > 5)
count = 1;
readerView.openFile("/mnt/sdcard/pdf/" + count + ".pdf", "");
Log.e("Inside onCreateView count is ", "" + count);
count++;
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity(), "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
/*v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});*/
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Log.d("PDFVIEW", "onDestroyView");
try {
if (readerView != null) {
readerView.clear();
// readerView.clearAllField(5);
// readerView.destroyDrawingCache();
// readerView.
// readerView=null;
// mPDFView.purgeMemory();
// mPDFView.destroy();//added to force release memory
// mPDFView = null;
}
Log.e("Fragment onDestroyView ", " onDestroyView readerView is "+readerView);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my custom viewpager class
package com.android.ho
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import com.sph.bh.ImageOnTapCallback;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.Toast;
public class ViewPagerWithTapGestreDetection extends ViewPager {
private ImageOnTapCallback imageOnTapCallback;
private GestureDetector tapGestureDetector;
private OnGestureListener mGestureListener;
public ViewPagerWithTapGestreDetection(Context context) {
super(context);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
public ViewPagerWithTapGestreDetection(Context context, AttributeSet attrs) {
super(context, attrs);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//Don't let any touches be passed down to the children automatically
Log.d("onInterceptTouchEvent ", "onInterceptTouchEvent");
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("onTouchEvent", "onTouchEvent");
if (imageOnTapCallback != null) {
tapGestureDetector.onTouchEvent(event);
}
return super.onTouchEvent(event);
}
public ImageOnTapCallback getImageOnTapCallback() {
return imageOnTapCallback;
}
public void setImageOnTapCallback(ImageOnTapCallback imageOnTapCallback) {
this.imageOnTapCallback = imageOnTapCallback;
}
public class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.d("onSingleTapConfirmed", "onSingleTapConfirmed");
if (null != imageOnTapCallback) {
imageOnTapCallback.tapDetected();
}
return super.onSingleTapConfirmed(e);
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.d("onDoubleTap", "onDoubleTap");
return super.onDoubleTap(e);
}
#Override
public void onLongPress(MotionEvent e) {
Log.d("onLongPress", "onLongPress");
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.d("onScroll", "onScroll");
return super.onScroll(e1, e2, distanceX, distanceY);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.e("onFling ", "onFling");
return super.onFling(e1, e2, velocityX, velocityY);
}
}
}
I think onInterceptTouchEvent intercept them.
Well, you are returning true from onInterceptTouchEvent(), which means, that as a ViewGroup you do not want any touch event to be passed to children, instead pass that touch event to onTouchEvent().
You should listen for event in onInterceptTouchEvent() return false until you see that this is such a gesture, that shouldn't be handled by children. And on that point only you should return true.

onClick is not called in my viewpager

I have a viewpager with several fragments in the viewpager.I need to handle click event.I have already implement the onTouch event,but its not trigger for click event.When i swiping onTouch is triggering.I don't know why it's not trigger for click event.
This is my viewpager class
package com.android.ho;
import com.sph.custom.ViewPagerWithTapGestreDetection;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class PDFActivity extends FragmentActivity implements ImageOnTapCallback,OnPageChangeListener{
static final int ITEMS = 20;
MyAdapter mAdapter;
//ViewPager mPager;
ViewPagerWithTapGestreDetection mPager;
//ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
try {
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPagerWithTapGestreDetection) findViewById(R.id.pager);
mPager.setId(5000);
mPager.setImageOnTapCallback(this);
mPager.setAdapter(mAdapter);
//mPager.setOffscreenPageLimit(1);
mPager.setOnPageChangeListener(this);
/*
Button button = (Button) findViewById(R.id.first);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.last);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(ITEMS - 1);
}
});
*/
mPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show image
return MyFragment.newInstance("1.pdf");
case 1: // Fragment # 1 - This will show image
return MyFragment.newInstance("2.pdf");
case 2: // Fragment # 1 - This will show image
return MyFragment.newInstance("3.pdf");
case 3: // Fragment # 1 - This will show image
return MyFragment.newInstance("4.pdf");
case 4: // Fragment # 1 - This will show image
return MyFragment.newInstance("5.pdf");
default:// Fragment # 2-9 - Will show list
return MyFragment.newInstance("1.pdf");
}
}
}
#Override
public void tapDetected() {
// TODO Auto-generated method stub
Log.e("tapDetected", "tapDetected");
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageScrollStateChanged", "onPageScrollStateChanged");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
Log.e("onPageScrolled", "onPageScrolled");
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageSelected", "onPageSelected");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("onDestroy", "onDestroy onDestroy onDestroy");
}
}
This is my fragment class
package com.android.ho;
import java.io.File;
import java.io.InputStream;
import com.epapyrus.plugpdf.core.viewer.ReaderView;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MyFragment extends Fragment{
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static int count = 1;
static String file;
TextView txt;
ReaderView readerView;
public static final MyFragment newInstance(String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
file = message;
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
try {
File fl = new File(Environment.getExternalStorageDirectory(), "/pdf/2.pdf");
readerView = (ReaderView) v.findViewById(R.id.pdfviews);
//readerView.setOnClickListener(this);
Log.e("readerView", fl.toString());
v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return true;
}
});
// readerView.openFile("/mnt/sdcard/pdf/1.pdf","");
if (count > 5)
count = 1;
readerView.openFile("/mnt/sdcard/pdf/" + count + ".pdf", "");
Log.e("Inside onCreateView count is ", "" + count);
count++;
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity(), "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
/*v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});*/
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Log.d("PDFVIEW", "onDestroyView");
try {
if (readerView != null) {
readerView.clear();
// readerView.clearAllField(5);
// readerView.destroyDrawingCache();
// readerView.
// readerView=null;
// mPDFView.purgeMemory();
// mPDFView.destroy();//added to force release memory
// mPDFView = null;
}
Log.e("Fragment onDestroyView ", " onDestroyView readerView is "+readerView);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my custom viewpager class
package com.android.ho
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import com.sph.bh.ImageOnTapCallback;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.Toast;
public class ViewPagerWithTapGestreDetection extends ViewPager {
private ImageOnTapCallback imageOnTapCallback;
private GestureDetector tapGestureDetector;
private OnGestureListener mGestureListener;
public ViewPagerWithTapGestreDetection(Context context) {
super(context);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
public ViewPagerWithTapGestreDetection(Context context, AttributeSet attrs) {
super(context, attrs);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//Don't let any touches be passed down to the children automatically
Log.d("onInterceptTouchEvent ", "onInterceptTouchEvent");
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("onTouchEvent", "onTouchEvent");
if (imageOnTapCallback != null) {
tapGestureDetector.onTouchEvent(event);
}
return super.onTouchEvent(event);
}
public ImageOnTapCallback getImageOnTapCallback() {
return imageOnTapCallback;
}
public void setImageOnTapCallback(ImageOnTapCallback imageOnTapCallback) {
this.imageOnTapCallback = imageOnTapCallback;
}
public class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.d("onSingleTapConfirmed", "onSingleTapConfirmed");
if (null != imageOnTapCallback) {
imageOnTapCallback.tapDetected();
}
return super.onSingleTapConfirmed(e);
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.d("onDoubleTap", "onDoubleTap");
return super.onDoubleTap(e);
}
#Override
public void onLongPress(MotionEvent e) {
Log.d("onLongPress", "onLongPress");
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.d("onScroll", "onScroll");
return super.onScroll(e1, e2, distanceX, distanceY);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.e("onFling ", "onFling");
return super.onFling(e1, e2, velocityX, velocityY);
}
}
}
Now when i click it identified by the onInterceptTouchEvent in the ViewPagerWithTapGestreDetection class.So i need to view a Horizontal scrollbar when i click.Is it the correct way to call it inside onInterceptTouchEvent ?

Categories

Resources