Getting nothing while calling performClick() function - Android - java

I'm new to Android developing and now I'm trying to simulate click on my AutoCompleteTextView object.
I'm expecting default android's keyboard appearance with the possibility to type something at the element
Here is a simple function, where I'm trying to perform it:
private void someTestMethodName() {
AutoCompleteTextView tagSearchInput = findViewById(R.id.autoCompleteTextView);
tagSearchInput.performClick();
}
And here is .xml element defining:
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView"
android:text="TextView"
android:layout_width="188dp"
android:layout_height="62dp"
android:layout_alignParentStart="true"
android:layout_marginStart="108dp"
android:layout_alignParentTop="true"
android:layout_marginTop="292dp"/>

Calling performClick on a TextView does not pop up the soft keyboard, but you can quite easily do that yourself:
private void someTestMethodName() {
AutoCompleteTextView tagSearchInput = findViewById(R.id.autoCompleteTextView);
showSoftKeyboard(tagSearchInput);
}
public void showSoftKeyboard(View view){
if(view.requestFocus()){
InputMethodManager imm =(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view,InputMethodManager.SHOW_IMPLICIT);
}
}
More information can be found here: https://github.com/codepath/android_guides/wiki/Working-with-the-Soft-Keyboard

i never used performClick, you cant use setOnClickListener to catch a click
tagSearchInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do somthing
}
});

Related

Adding basic click animation to dynamic buttons

I have a simple button that looks like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:tag="general"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#343535"
android:orientation="vertical"
tools:context=".fragments.GeneralFragment">
<Button
android:id="#+id/hello"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/hello" />
Instead of static, these buttons should now be dynamic
Button button = (Button) layout.getChildAt(0);
for(String text : readFromSharedPreferences) {
// Set the layout
Button btn = new Button(this.getContext());
btn.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
btn.setText(text);
btn.setTag(text);
btn.setLayoutParams(button.getLayoutParams());
btn.setBackground(button.getBackground());
layout.addView(btn);
The static button has an animation when I click on it. That looks like this:
But the dynamic button has no animation. So when I click on it, nothing happens. That looks like this:
How can I add this animation to my dynamic buttons?
Update
I have figured out that my loop contains an on-touch listener. That looks like this:
btn.setOnTouchListener(new OnSwipeTouchListener(getContext()) {
// No code in here
});
If I remove that listener (even if it contains no code), the animation works great but I would like to keep it, because of my swipe function that is placed into it.
That is my whole code:
// Swiping to link
btn.setOnTouchListener(new OnSwipeTouchListener(getContext()) {
#Override
public void onSwipeLeft() {
super.onSwipeLeft();
// Alert to ask
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Delete");
builder.setMessage("Do you want to delete?");
// Delete
builder.setPositiveButton("Yes", (dialog, which) -> {
// Set the SharedPreferences as String
ArrayList<String> currentSharedPreferences = readFromSharedPreferences(getContext());
currentSharedPreferences.remove(btn.getTag().toString());
Gson gson = new Gson();
String currentSharedPreferencesAsText = gson.toJson(currentSharedPreferences);
// Update the SharedPreference k-text
SharedPreferences mPrefs = getContext().getSharedPreferences("k-texts", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
prefsEditor.putString("k-text", currentSharedPreferencesAsText);
prefsEditor.apply();
// Start the animation
btn.animate()
.translationX(-btn.getWidth())
.alpha(0.0f)
.setDuration(300)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
btn.clearAnimation();
btn.setVisibility(View.GONE);
Snackbar.make(view, "Entry deleted.", Snackbar.LENGTH_LONG).setAction("Delete", null).show();
}
});
});
// Cancel
builder.setNegativeButton("No", (dialog, which) -> {
// Silence is golden
});
builder.show();
}
#Override
public void onClick() {
MainActivity mainActivity = new MainActivity();
Tts tts = new Tts(getContext(), _mediaPlayer, mainActivity.barTop, mainActivity.barBottom);
try {
tts.say(btn.getTag().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
Well I could use
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
Then the animation will work but onClick() wouldn't work anymore.
Another update
I had a similar problem on another view. There my static button was not having a click effect. Then I have just simply added android:foreground="?attr/selectableItemBackground" and it worked! The same way I have just tried with my dynamic button. So I have added btn.setForeground(button.getForeground()); but that doesn't do anything.
Use MaterialButton instead of Button. MaterialButton is a subtype of Button that supports additional features. The Button that is in your XML layout is actually a MaterialButton if you're using a Material Components theme. The theme automatically swaps out Buttons for MaterialButtons when your XML is inflated. So, when dynamically creating buttons in your Java code, you must use MaterialButton if you want it to match the original.
Also, when using MaterialButton, never call setBackground() because this causes undefined behavior. It likely will prevent the ripple effect from occurring as well.
Alternatively, you can define your Button in its own XML file, even with the layout params it needs for LinearLayout. Then inflate the XML each time you need another button.
for(String text : readFromSharedPreferences) {
Button btn = requireContext().getLayoutInflater()
.inflate(R.layout.my_button, layout, true); // true adds it to layout
btn.setText(text);
btn.setTag(text);
}

How can I swap images on button click?

Essentially All the ImageButton has to do (InactiveButton) is switch to an image when pressed. I have no clue where to start with this because I am new to Android Studio.
I have tried using the selector class but I don't know what it's supposed to accomplish. When I use other's code such as public void buttonOnClick(View v), android studio says it's deprecated?
XML layout:
<ImageButton
android:id="#+id/InactiveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/button_default" />
EDIT 1: I have added the following code and still got an "annotations are not allowed here" #override on line 52, and cannot resolve symbol v on line 53.
Picture of error
EDIT 2: Image of final error on line 50
Location of error
Actual Compiler Message
What Ferran has said is absolutely right.
You need to implement it in correct way.
Firstly define you image view before onCreate method so that it will be treated as global variable and advantage of this is you can use it anywhere in same activity.
Like
ImageButton inactiveButton;
Secondly, find its view by using FindViewById in onCreate method.
Like
inactiveButton = convertView.findViewById(R.id.InactiveButton);
Next, you can implement onClickListener on inactiveButton by using two ways:
1. You can implement "implements View.OnClickListener" to your activity by using inactiveButton.setOnClickListener(this); This will prompt you to implement "android.view.View.OnClickListener" to your activity or fragment. Implement this method this will add onClick method and here you can write you code to change image in the image button
#Override
public void onClick(View v) {
// add this, this will help you to implement multiple clicklisteners and you can add different methods in each click listener
switch (v.getId())
{
case R.id.InactiveButton:
inactiveButton.setImageResource(R.drawable.otherimage);
break;
default:break;
}
}
You can directly write OnClickListener, you need to keep this in main method
inactiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inactiveButton.setImageResource(R.drawable.otherimage);
}
});
Hope this will help you. I know I have added a lot of information but I think it will help you in long run. You can check images for more clarity then you can easily understad you flaw.
Regards
Amanpreet
You can change the image like this:
ImageView someImageView= (ImageView) findViewById(R.id.some_image_view);
imageView.setImageResource(R.drawable.some_image);
In your onCreate method from your Activity
ImageButton inactiveButton = convertView.findViewById(R.id.InactiveButton);
Now, you have a reference to your ImageView.
Then, you need to define what to do when you click on it.
inactiveButton .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// put here the code when ImageView is clicked
// to change the ImageView image
inactiveButton.setImageResource(R.drawable.otherimage);
}
});
That's all.

Soft keyboard auto show when use AsyncTask

I don't know why when I use AsyncTask to load data to an Adapter, after AsyncTask finishes, the soft keyboard shows on screen.
There is a Edittext in the activity. If I delete the EditText on the Activity, after the AsyncTask finishes, the soft keyboard does not show.
I use this code on onPostExecute() but it does not work:
protected void onPostExecute(String[] result) {
hideSoftKeyboard(SearchActivity.this);
RecommendAdapter mAdap = new RecommendAdapter(con, mLocation);
mListview.setAdapter(mAdap);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity
.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
Now I know the answer.It because I use so it always focus on .Add the android:focusable="true"
android:focusableInTouchMode="true" to the Layout so the soft keyboard not show.

edittext validation [duplicate]

This question already has answers here:
Android EditText.setError() yields invisible error text
(5 answers)
Closed 9 years ago.
I have following small block of code to set validation on edit text when a button is pressed and display the validation message in a dialog.
Java Code
setContentView(R.layout.addnewcontacts);
Button buttonSave = (Button) findViewById(R.id.buttonSave);
final EditText editTextName = (EditText) findViewById(R.id.editTextName);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (editTextName.getText().toString().length() == 0) {
editTextName.setError( "First name is required!" );
}
}
});
}
Code is working fine but the popup is not displaying text in it.
Screen shot :
Why popup is not showing text?
Call EditText.setError() with a SpannableStringBuilder object.
Check this previous SO question: Android EditText.setError() yields invisible error text
Use EditText.setTextColor(int color) to set the required color for the text element.
Just add edittext color into your xml file.
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#android:color/black" />
it's very simple just follow the below code it is working fine.
final EditText et=(EditText)findViewById(R.id.editText1);
Button bt=(Button)findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(et.getText().toString().length()==0){
et.setError("it is wrong");
}
}
});
please check the theme you have applied .Use basic theme to check error text

Setting up buttons for Android

Here is my problem. I setup the buttons exactly the way they are setup in the Android documentation, but I am getting a warning, and the button will not do anything.
Here is my Java code:
package com.variDice;
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
public class VariDiceActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//die1Clicked();
}
private void die1Clicked() {
ImageButton die1button = (ImageButton)findViewById(R.id.die1button);
die1button.setImageResource(R.drawable.icon);
}
}
...and the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1" android:layout_gravity="center_horizontal">
<ImageView
android:id="#+id/varidice_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="#drawable/icon"></ImageView>
<ImageButton
android:id="#+id/die1button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#null"></ImageButton>
</LinearLayout>
...and the warning:
The method die1Clicked from the type VariDiceActivity is never used locally.
I must say that I am completely new to Android development. I made my app for the iPhone, and I am now trying to make a version for the android. The iPhone version was sooo much easier, because of the better interface builder (so I can just make an action and connect it to the button that way), so this is almost impossibly hard for me to understand. In other words, I do not understand how you connect an action to the button. Could somebody please tell me what I am doing wrong?
Try this in your xml:
<ImageButton
android:id="#+id/die1button"
android:onClick="die1Clicked"
...></ImageButton>
And in your code, change the method signature to:
public void die1Clicked(android.view.View v) {
ImageButton die1button = (ImageButton)findViewById(R.id.die1button);
die1button.setImageResource(R.drawable.icon);
}
Here is the Android Button tutorial.
To bind some behavior to an UI button, you need to register a listener that receives notifications of a certain event type. In your case, you register a OnClickListener (for the click event); just like in the following snippet:
// create the implementation of OnClickListener
private OnClickListener mDie1Listener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
protected void onCreate(Bundle savedValues) {
...
// get the button from layout
Button button = (Button)findViewById(R.id.die1button);
// register the onClick listener with the implementation above
button.setOnClickListener(mDie1Listener);
...
}
You need to add a click listener to your button. Put this in your onCreate():
ImageButton die1button = (ImageButton)findViewById(R.id.die1button);
die1button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// What to do when the button is clicked
});
Most answers on SO tend to use 'setOnClickListener' instead of using xml properties.
I personally prefer using xml for making items clickable in android.
The mistake you have made is setting your function as private. The function which gets called after clicking the item should be public.
There are 3 things you should keep in mind:
Define the 2 properties in xml.
android:clickable="true"
android:onClick="functionName"
Define that function in the Activity file. Make sure to keep the function public.
public void functionName(View v) {
// TODO Auto-generated method stub
}
Make sure to pass 'View v' as an argument for that function.

Categories