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.
Related
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);
}
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.
I'm brand new to this whole android coding and im trying to setup a login page for my app. I created the login button and im trying to setup the onClick thing for it but its not working. Ill paste my java file below
package com.example.user_000.appname;
import android.widget.EditText;
import android.view.View;
public class onClick {
EditText username = (EditText)findViewById(R.id.username);
EditText password = (EditText)findViewById(R.id.password);
public void login(View view){
if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")){
//correcct password
} else {
//wrong password
}
}
}
I am not changing anything in your code just i am providing you a way to get it correctly as you are missing lot of things
Button's onClick() method can be set up basically in 3 ways
Very first from xml side when you declare a button
<Button
android:layout_height="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="login"/>
And then just make a method in associated java class with the same name as given in XML file like this
public void login(View v)
{
//do whatever you want here
}
Second way you can make an inner implementation anywhere in your class by simply making onClickListner() on Button,but you have to make sure to get button on java side by findViewById() method once you got it then you can set like this
Button b = (Button)findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff here
}
});
third way is also simple you can implement OnClickListner in your whole class and then you can use it for multiple views clicks but i would say if you have a button only then no need to use this you can use above two methods in this one you can do this
b.setOnClickListener(this);
It will show you an error that methods are not implemented and then you can just use Alt + Enter and onClick() method will be implemented
#Override
public void onClick(View v) {
if(v.getId()==R.id.yourId) {
//do stuff here
}
}
Some useful links are below
Best practice for defining button events in android
Difference between OnClick() event and OnClickListener?
Button Click Listeners in Android
Basically, the problem is pretty straight-forward if you read the title.
I started my test application for testing purposes and when I'm at the main menu, there is that bar with the application name above and when I click on any button that triggers a new activity, the bar disappears.
http://i.stack.imgur.com/uI70f.png
After clicking, in this example, "What's the meaning of life?" button, the result looks like this
http://i.stack.imgur.com/7mvmY.png
The codes that are used in order to make the button are as follows:
options_menu.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What is the meaning of life?"
android:onClick="ShowLifeMeaning"
android:textAllCaps="false"
android:id="#+id/button2"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true" />
Life.java
public class Life extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.meaning_of_life);
}
#Override
public void onBackPressed() {
finish();
}
MainActivity.java
public void ShowLifeMeaning(View view) {
startActivity(new Intent(this, Life.class));
}
You can try using
public class Life extends ActionBarActivity
Hi I think it 's because of theme, in your manifest file maybe you right this code for theme :
theme."your theme".NoActionbar or something like this.
if you remove it , it would be correct
You need to use ActionBarActivity.
But this class being deprecated , you can use AppCompatActivity with which you can support actionBar starting from API 7 and it supports fragments as well.
I make a Button and I want to make onClick method in XML
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="#+id/button2"
android:onClick="maysara"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/button"
android:layout_alignStart="#+id/button"
android:layout_marginTop="63dp" />
Then I go to Java code to make the method "maysara"
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void maysara(View v){
**if(v.getId()==findViewById(R.id.button2))**
Toast.makeText(this,"button2",Toast.LENGTH_SHORT).show();}}
But I got an error in if statement >>> I really dont know why #?!
Check the return type of findViewById() which is a view and you are comparing with v.getId() which is id. You should not compare this.
public View findViewById (int id)
Just use like this
public void maysara(View v){
Toast.makeText(this,"button2",Toast.LENGTH_SHORT).show();
}
It help you.
I know this has an answer, but I thought I'd add one.
You are declaring
android:onClick="maysara"
as the onClick method in your xml for this button.
There is no need to do a check on which button is clicking, as you have explicitly defined this in your xml.
So within your mayasara method, you only need to show what you want to do, not a check on the button clicking.
public void maysara(View v){
<Button
android:id="#+id/button1"
android:onClick="maysara"
<Button
android:id="#+id/button2"
android:onClick="maysara"
A switch statement is a much better option, as you do not need to check for the value of R.id.button2 as you have in your if statement. Checking those values for this type of function is a clumsy way of programming.
public void maysara(View v){
switch(v.getId()) {
case R.id.button1:
// to do
break;
case R.id.button2:
// to do
break;