I am developing a program in android studio. I want when I click a button then action will perform at the same time.
Function:
1st - Start count clicks
2nd - after 5 seconds that button disable
setDelay = new Handler();
btn = (Button) findViewById(R.id.bt);
final Button disableMe = (Button) findViewById(R.id.bt);
final TextView text = (TextView) findViewById(R.id.timeUp);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
startDelay = new Runnable(){
#Override
public void run(){
text.setText("Time Up!");
disableMe.setEnabled(false);
}
};
setDelay.postDelayed(startDelay, 5000);
}
});
txv = (TextView) findViewById(R.id.tx);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCounter ++;
txv.setText(Integer.toString(mCounter));
}
});
This can help
private int clicks = 0;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
final Button b = (Button)v;
if (clicks == 0){
// Means its the first time that a user click the button
// Start a thread that is going to disable the button after 5 seconds from first click
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run() {
b.setText("Time up");
b.setEnabled(false);
// Showing user clicks after button is disabled
showClicks();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
// Here we are just counting . . . . including the first click
countClicks();
}
});
Count clicks method
private void countClicks(){
++clicks;
// You can update your text view here
}
Showing total clicks
private void showClicks(){
Toast.makeText(this, Integer.toString(clicks), Toast.LENGTH_SHORT).show();
}
Just use a boolean variable to tell if the disable Runnable is started:
button.setOnClickListener(new View.OnClickListener() {
boolean disableRunnableStarted = false;
Runnable disableRunnable = new Runnable(){
#Override
public void run(){
//Running on UI thread to update button
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
button.setEnabled(false);
}
});
}
};
#Override
public void onClick(View v) {
if(!disableRunnableStarted) {
Log.d(TAG,"Starting disable runnable and incrementing counter...");
new Handler().postDelayed(disableRunnable,5000);
disableRunnableStarted = true;
//Here increment your counter
} else {
Log.d(TAG,"Just incrementing counter...");
//Here increment your counter
}
}
});
Replace MainActivity with your Activity's name, if executing in a Fragment replace by getActivity().
create new list like this :
ArrayList <View.OnClickListener> clickList = new ArrayList<>();
then add all your Listener :
final Runnable startDelay;
clickList.add(new View.OnClickListener(){
#Override
public void onClick(View v){
if (startDelay != null)
return;
startDelay = new Runnable(){
#Override
public void run(){
text.setText("Time Up!");
disableMe.setEnabled(false);
}
};
setDelay.postDelayed(startDelay, 5000);
}
});
clickList.add(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCounter ++;
txv.setText(Integer.toString(mCounter));
}
});
then , in your button add this Listener:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (View.OnClickListener c : clickList)
c.onClick(view);
}
});
Related
I am using WebView to view my offline webpage which contains few html pages named 1.html, 2.html and so on with main page index.html.It has only one Mainactivity and for now I'm using below code to exit the app when pressed twice. I want to add functionality to go back to previous page if pressed once and exit the app when pressed twice.
Here is the code for now which exit the app if pressed twice
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit",
Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
Any help would be much much appreciated.
boolean isDouble = false;
private int DURATION = 1000;
#Override
public void onBackPressed() {
if (isDouble) {
finishAndRemoveTask();
return;
}
isDouble = true;
finish();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
isDouble=false;
}
}, DURATION);
}
Im not so sure its a good pattern because it would be confusing to the user, if you want double back to exit the activity, and a single back to go to the previous page, you should consider adding a back button to activity title where users would have a dedicated back button. Notwithstanding though, what you can do in this case is go to the previous page once the timeout is expired as shown below
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
//super.onBackPressed(); use finish instead to close activity
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit",Toast.LENGTH_SHORT).show();
goBack();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
public void goBack(){
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
}
Hope it helps, Goodluck
Trying to make a "click counter" game in android studio.
int clicked = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = (TextView) findViewById(R.id.counter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked++;
text.setText(clicked);
}
});
}
This is the code i set up for the counter. Any ideas about what i might be doing wrong?
Try: #Override public void onClick(View v) { clicked+=1; text.setText(String.valueOf(clicked);
text.invalidate();}
I wrote an Android app with toggle button but toggle button does not work well at the first time. But after unchecking, if you try again, it is working properly after that.
I listed below my codes.
Which codes I have to add to activate it for the first time?
public class MainActivity extends Activity{
private ToggleButton togg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
togg = (ToggleButton) findViewById(R.id.toggleButton1);
}
public void nameOfMethod(View v){
togg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (togg.isChecked()) {
//Toast.makeText(MainActivity.this, "Servise bağlanılıyor...", Toast.LENGTH_SHORT).show();
new Thread(new ClientThread()).start();
} else {
Toast.makeText(MainActivity.this, "Bağlantı sonlandırılıyor...", Toast.LENGTH_SHORT).show();
}
}
});
}
in .xml file:
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:onClick="nameOfMethod"
android:textOn="Bağlantıyı bitir"
android:textOff="Bağlantıyı başlat" />
EDIT: It works just fine like that:
public class MainActivity extends Activity{
private ToggleButton togg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
togg = (ToggleButton) findViewById(R.id.toggleButton1);
togg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (togg.isChecked()) {
//Toast.makeText(MainActivity.this, "Servise bağlanılıyor...", Toast.LENGTH_SHORT).show();
new Thread(new ClientThread()).start();
} else {
Toast.makeText(MainActivity.this, "Bağlantı sonlandırılıyor...", Toast.LENGTH_SHORT).show();
}
}
});
}
with moving setOnClickListener method to onCreate(Bundle savedInstanceState) and deleting android:OnClick method in .xml file...
You should set checked status for the toggle button in xml or in your code.
Xml
android:checked="true"
Or code:
togg = (ToggleButton) findViewById(R.id.toggleButton1);
togg.setChecked(true);
Otherwise, you can use
togg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO
}
});
instead of OnClickListener().
It will be ok if you still want to use OnClickListener, but remember to put it it onCreate instead of putting it in nameOfMethod. (Or remember call nameOfMethod in onCreate)
To put it onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
togg = (ToggleButton) findViewById(R.id.toggleButton1);
togg.setChecked(false);
togg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
}
});
}
Well it appears that you're setting your click listener AFTER the toggle button is selected the first time, which explains the behavior you're getting.
Move the code to set your listener outside of nameOfMethod() and it should work.
EDIT: Sorry If I wasn't clear, just remove the setOnClickListener method from your nameOfMethod(). nameOfMethod() is what will be called each time the toggle button is selected, so it really makes no sense to set a listener each time it's touched..that is why you're getting such unusual behavior.
Instead, in your nameOfMethod(), just go right ahead and set up your conditions based on the state of the toggleButton
if(toggleButton.isSelected()){
..........
{
else
.......
I have a website with href in it which redirected me to https
<a id="mA" href="javascript:pLogin(2)" class="login-link__link private-cab-link"><i class="icon-user"></i>Авторизация</a>
So, I can click on it by JavaScript. It works in chrome console
javascript:(function(){document.getElementById('mA').click();})()
Now I'm trying to do the same in WebView by clicking my app's button.
public class RostelecomLoginActivity extends Activity {
WebView webView;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_rostelecom_login);
Intent webIntent = getIntent();
String url = webIntent.getStringExtra("url");
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new MeWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSaveFormData(true);
webView.getSettings().setSavePassword(true);
webView.loadUrl(url);
Button buttoner = (Button) findViewById(R.id.button1);
buttoner.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
webView.loadUrl("javascript:(function(){document.getElementById('mA').click();})()");
}
});
}
}
I'm using MyWebViewClient to allow all certificates
public class MeWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
}
The js injection doesn't work. If I click on href in WebView it works.
What can be wrong?
click() isn't implemented in android js interface, you have to use HTML DOM Event Object, like this:
webView.loadUrl("javascript:(function(){"+
"l=document.getElementById('mA');"+
"e=document.createEvent('HTMLEvents');"+
"e.initEvent('click',true,true);"+
"l.dispatchEvent(e);"+
"})()");
You'll have to add a javaScript interface to the WebView to call a JavaScript function from android code.
Try something like this:-
Button buttoner = (Button) findViewById(R.id.button1);
buttoner.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
JavascriptInterface javasriptInterface = new JavascriptInterface(RostelecomLoginActivity.this);
webView.addJavascriptInterface(javasriptInterface, "MyInterface");
webView.loadUrl("javascript:(function(){document.getElementById('mA').click();})()");
}
});
I want to search and highlight a word in android webview, I tried with this code but it is not working. My code is here:
webview.findAll("a");
webview.setSelected(true);
webview.findNext(true);
try {
for (Method m : WebView.class.getDeclaredMethods()) {
if (m.getName().equals("setFindIsUp")) {
// m.setAccessible(true);
m.invoke(webview, true);
break;
}
}
} catch (Exception ignored)
{
Log.i("highlight error", ignored.toString());
}
This code is not setting any highlight on the selected word or not giving any error so please tell me how to search for and select a word in a webview ,currently i am trying for android version 3.2?
Setup a search button on your WebView layout.
Set up the WebView, and then a Search Button as follows. The popup dialog has a Cancel Button, a Search Button and an Edit Text for the search term. When search is pressed, each match of the EditText string will be highlighted in the WebView.
final Activity activity = this;
webView = (WebView) findViewById(R.id.yourWebView);
webView.setScrollbarFadingEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.clearCache(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.setTitle("Loading Web Page");
progressDialog.setIcon(R.drawable.ic_menu_allfriends);
progressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
webView.destroy();
finish();
} });
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1000);
progressDialog.incrementProgressBy(progress);
if(progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
webView.loadUrl(yourStringURL);
Button search = (Button) findViewById(R.id.butSearch);
search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//set up button for search keyword of the webView
final Dialog dSearch = new Dialog(myActivity.this);
dSearch.setContentView(R.layout.search_keyword);
dSearch.setCancelable(true);
dSearch.setTitle(getString(R.string.yourTitle));
Button cancel = (Button) dSearch.findViewById(R.id.searchCancel);
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dSearch.dismiss();
}
});
Button search = (Button) dSearch.findViewById(R.id.searchAdd);
search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText etkw = (EditText) dSearch.findViewById(R.id.searchword);
String keyword = etkw.getText().toString();
dSearch.dismiss();
webView.findAll(keyword);
try
{
Method m = WebView.class.getMethod("setFindIsUp", Boolean.TYPE);
m.invoke(webView, true);
}
catch (Throwable ignored){}
}
});
dSearch.show();
}
});