How to use radiobuttons with array? - java

I was interested in making an APP for Android with 30 personality profile questions, where each question will have two alternatives of choice. I thought about using RadioButton, but since there are 30 questions I would not like to include them all on the screen at once, I would like to display only one question with two alternatives and each selection of one of the alternatives already called the other question.
Is it possible to do this without creating 30 activities?
I saw that it might be possible to do array, but I do not know how to run it from one issue to another.
Thank you so much!!!

This code achieves the required functionality. It is very basic and can be improved as per your need. Simply add this activity and layout to your project.
Java File: This code uses a single layout and recreate the view for next question on Radio Button Click
public class QuestionsActivity extends AppCompatActivity implements
RadioGroup.OnCheckedChangeListener{
LinkedHashMap<String,RadioGroup> questionList;
LinkedHashMap<String,String> answerList;
ArrayList<String> keys=new ArrayList<>();
int keyCounter=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
questionList=new LinkedHashMap<>(); //This Map contains all the questions with two radio button (options)
answerList=new LinkedHashMap<>(); //This Map will contain question along with selected answer.
initQuestions(); //This method will add 30 questions with options
keys.addAll(questionList.keySet());
showQuestions(keys.get(keyCounter));//This method will show the first question
}
private void showQuestions(String key) {
TextView textView=(TextView)findViewById(R.id.tv_question);
textView.setText(key);
LinearLayout layout =(LinearLayout)findViewById(R.id.questionsLayout);
layout.removeAllViews();
RadioGroup rg=questionList.get(key);
rg.setOrientation(LinearLayout.HORIZONTAL);
layout.addView(rg);
rg.setOnCheckedChangeListener(this);
}
private void initQuestions() {
for (int i = 1; i <=3; i++) {
RadioGroup rg=new RadioGroup(this);
RadioButton rb1 =new RadioButton(this);
rb1.setText("Q "+i+" RadioButton 1");
RadioButton rb2 =new RadioButton(this);
rb2.setText("Q "+i+" RadioButton 2");
rg.addView(rb1);rg.addView(rb2);
questionList.put("Question "+i,rg);
}
}
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
RadioButton rb=(RadioButton) findViewById(group.getCheckedRadioButtonId());
if(keyCounter<questionList.size()) {
answerList.put(keys.get(keyCounter),rb.getText().toString()); // Putting the question and selected answer to 'answerList' map.
keyCounter++;
if(keyCounter<questionList.size()) {
showQuestions(keys.get(keyCounter));// showing the next question.
}
}else {
Toast.makeText(this, "You've answered all the questions.", Toast.LENGTH_SHORT).show();
}
for (String s : answerList.keySet()) {
System.out.println("Q--> "+s+", A--> "+answerList.get(s)); // Here you can see all the questions and selected answers on your logs(AndroidMonitor).
}
}
}
layout file : This file contains a textView which will be used to show question and a linear layout which contains the RadioGroup
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="edios.endlessscrollrecycler.QuestionsActivity">
<TextView
android:id="#+id/tv_question"
android:layout_marginTop="10dp"
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:orientation="horizontal"
android:id="#+id/questionsLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"></LinearLayout>
</LinearLayout>

Related

How to avoid "jumpy" issue when interacting with soft keyboard visibility

Currently, we have an app with the following requirements
Must use android:windowSoftInputMode="adjustPan"
Use ViewCompat.setWindowInsetsAnimationCallback and ViewCompat.setOnApplyWindowInsetsListener to interact with soft keyboard visibility with smooth animation.
Here is our code, when interacting with soft keyboard visibility. It works pretty well in the case, when our EditText is not scrollable.
The animation went pretty well, when keyboard is showing and hiding.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText editText;
LinearLayout toolbar;
FrameLayout keyboardView;
private int systemBarsHeight = 0;
private int keyboardHeightWhenVisible = 0;
private boolean keyboardVisible = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.edit_text);
toolbar = findViewById(R.id.toolbar);
keyboardView = findViewById(R.id.keyboard_view);
final View rootView = getWindow().getDecorView().getRootView();
ViewCompat.setOnApplyWindowInsetsListener(rootView, (v, insets) -> {
boolean imeVisible = insets.isVisible(WindowInsetsCompat.Type.ime());
systemBarsHeight = insets.getInsets(WindowInsetsCompat.Type.systemBars()).bottom;
keyboardVisible = imeVisible;
if (keyboardVisible) {
keyboardHeightWhenVisible = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom;
}
// https://stackoverflow.com/questions/75325095/how-to-use-windowinsetscompat-correctly-to-listen-to-keyboard-height-change-in-a
return ViewCompat.onApplyWindowInsets(v, insets);
});
WindowInsetsAnimationCompat.Callback callback = new WindowInsetsAnimationCompat.Callback(
WindowInsetsAnimationCompat.Callback.DISPATCH_MODE_STOP
) {
#NonNull
#Override
public WindowInsetsCompat onProgress(#NonNull WindowInsetsCompat insets, #NonNull List<WindowInsetsAnimationCompat> runningAnimations) {
// Find an IME animation.
WindowInsetsAnimationCompat imeAnimation = null;
for (WindowInsetsAnimationCompat animation : runningAnimations) {
if ((animation.getTypeMask() & WindowInsetsCompat.Type.ime()) != 0) {
imeAnimation = animation;
break;
}
}
if (imeAnimation != null) {
int keyboardViewHeight;
if (keyboardVisible) {
keyboardViewHeight = (int) (keyboardHeightWhenVisible * imeAnimation.getInterpolatedFraction()) - systemBarsHeight;
} else {
keyboardViewHeight = (int) (keyboardHeightWhenVisible * (1.0-imeAnimation.getInterpolatedFraction())) - systemBarsHeight;
}
keyboardViewHeight = Math.max(0, keyboardViewHeight);
ViewGroup.LayoutParams params = keyboardView.getLayoutParams();
params.height = keyboardViewHeight;
keyboardView.setLayoutParams(params);
Log.i("CHEOK", "keyboardVisible = " + keyboardVisible + ", keyboardViewHeight = " + keyboardViewHeight);
}
return insets;
}
};
ViewCompat.setWindowInsetsAnimationCallback(rootView, callback);
}
}
activity_main.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="#+id/edit_text"
android:padding="16dp"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top" />
<LinearLayout
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#ffff00" />
<FrameLayout
android:id="#+id/keyboard_view"
android:background="#ff0000"
android:layout_width="match_parent"
android:layout_height="0dp" />
</LinearLayout>
Here is the outcome.
When EditText is not scrollable
However, our app becomes "jumpy", when the content of EditText is scrollable.
When EditText is scrollable, our app becomes "jumpy"
Does anyone know what is the root cause of this problem, and how we can resolve such?
A demo to demonstrate such an issue, can be downloaded from https://github.com/yccheok/programming-issue/tree/main/jumpy
Using both adjustPan and WindowInsetsAnimation seems to over-animating the content.
adjustPan - The activity's main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desirable than resizing, because the user may need to close the soft keyboard to get at and interact with obscured parts of the window.
This means that the activity is pushing its upper part until it's possible to make a room for the EditText widget (or its editable part) visible so that the user can see what they are typing.
And I do believe that Google developers provided the insets API to get the obsolete overwhelming stuff deprecated soon or later; for instance recently setting adjustResize programmatically is now deprecated as of API Level 30 and replaced with the inset API.
More verification of the inconvenience between adjustPan and WindowInsetsAnimation, try the below couple of scenarios in your sample repo:
Remove android:windowSoftInputMode="adjustPan"
Remove ViewCompat.setWindowInsetsAnimationCallback(rootView, callback);
Either scenario will work solely without having to worry about the jumpy/bouncy layout. But in case of the scenario no. 1, the red view appears because the activity area doesn't occupy the entire window screen (this requires to have a full screen app) with WindowCompat.setDecorFitsSystemWindows(getWindow(), false);. This tutorial deeply targets different aspects of insets API.
What I think the cause of this jumpy/bouncy behavior is that the adjustPan tries to do its job when the keyboard is shown; but eventually hard-coding the margins in the WindowInsetsAnimation wins the round and makes the layout bounce back at the end of the animation.
So, it's recommended to remove that adjustPan to keep the new fancy inset APIs up and running.
Or at least keep it at the manifest file, but disable it just before starting the animation and re-enable it again at the end of the animation (i.e., disable its panning behavior during the animation) using onPrepare() and onEnd() callbacks:
WindowInsetsAnimationCompat
.Callback callback = new WindowInsetsAnimationCompat.Callback(
WindowInsetsAnimationCompat.Callback.DISPATCH_MODE_STOP
) {
#Override
public void onPrepare(#NonNull WindowInsetsAnimationCompat animation) {
super.onPrepare(animation);
// disable adjustPan
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
}
#Override
public void onEnd(#NonNull WindowInsetsAnimationCompat animation) {
super.onEnd(animation);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
#NonNull
#Override
public WindowInsetsCompat onProgress(#NonNull WindowInsetsCompat insets, #NonNull List<WindowInsetsAnimationCompat> runningAnimations) {
// ... code is omitted for simplicity
}
};
But make sure that you also have a full screen app:
WindowCompat.setDecorFitsSystemWindows(getWindow(), false);

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 to listen for multiple GlobalLayout events

I am trying to listen for GlobalLayout using
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
int c=0;
#Override
public void onGlobalLayout() {
c++; //without removing the listener c will grow for ever even though there is no GlobalLayout events
view.setText(""+c);
}
});
but it's called endlessly.
I know I should remove the listener like this: view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
But I want to keep the listener alive for the next GlobalLayout events.
Currently I am just trying to listen for view position changing using this question
I tried onPreDraw but it is the same.
Is it possible to listen for several GlobalLayout events?
Thanks in advance.
The code you posted as an example shouldn't compile because of issues with accessing the variable c from the listener. If you try it, you should get the following error in Android Studio:
Variable 'c' is accessed from within inner class, needs to be final or effectively final
We can take the suggestion that error check suggests and create a one-element array as follows:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int[] c = {0};
final View[] view = {findViewById(R.id.textView)};
view[0].getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
c[0]++;
}
});
}
}
If you run this code against the following layout, you will see that the listener is called twice which I think corresponds to two layout passes:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
If the layout is somehow modified within the global layout listener, then it will trigger another layout and another call to the the listener. If the listener again makes a change, the listener will be called yet again and so on forever.
It would be helpful if you would post the actual code you are having trouble with or a simple project that demonstrates the problem. Is the layout somehow modified within the listener?
Update: As you say in one of your comments on this answer, your issue was that you made a change to a view in the global layout listener which triggered another layout and another call to the listener ad infinitum. Once you removed the code that made the layout change, that particular issue was resolved.
If you're just trying to trigger the code once the view position has changed, then you could probably just check if the x, y coordinates has changed before increasing the variable c
Something like this:
int c = 0;
int x = 0;
int y = 0;
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int x2 = view.getX();
int y2 = view.getY();
// do not increase c unless position has changed
if (x2 != x && y2 != y) {
c++;
// update coordinates values
x = x2;
y = y2;
}
}
});
you can set the Listener on your Viewes try to use view.addOnLayoutChangeListener
https://developer.android.com/reference/android/view/View.OnLayoutChangeListener
it will give you the old and new X&Y of your layout and you can adjust your view base on it
Simply add a flag to detect if it is a normal event or a setText() that is called by the listener and skip it if needed.
Code not tested. But I guess you will get the idea.
int c=0;
view.getViewTreeObserver().addOnGlobalLayoutListener(new CustomLayoutListener() {
int c=0;
#Override
public void onGlobalLayout() {
if(skipEvent)
return;
c++;
//flag skipEvent while performing setText()
skipEvent = true;
view.setText(""+c);
skipEvent = false;
}
});
class CustomLayoutListener extends ViewTreeObserver.OnGlobalLayoutListener {
static boolean skipEvent;
#Override
public void onGlobalLayout() {}
}

Multiple RadioButtons with one selectable value

So I'm have two RadioGroups, one for gender, one for unit type. User has to select value for both RadioGroups, but value of first selected group affects the value of secont group.
For example, if user is male and uses metric unit type one layout will be shown to him. If he's male but uses imperial unit, another layout will be shown to him.
My question is, how to have RadioButton onClick method inside of RadioButton onClick method?
Sorry, I don't know how to explain this better.
Here's the code:
public void dialogBodyFatMuskarciRadioButtonKliknut(View view){
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()){
case R.id.radioButtonDialogBodyFatSpolMuski:
if (checked)
public void dialogBodyFatRadioMetrickaJedinica(View view){
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()){
case R.id.radioButtonDialogBodyFatSpolMuski:
if (checked)
}
}
Didnt test this, but you could implement the logic something like this.
In your Manifest:
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gender_RadioGroup"
<RadioButton android:id="#+id/male"
android:text="#string/male"
android:onClick="onGenderRadioButtonClicked"/>
<RadioButton android:id="#+id/female"
android:text="#string/female"
android:onClick="onGenderRadioButtonClicked"/>
</RadioGroup>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/unit_type_RadioGroup"
<RadioButton android:id="#+id/metric_unit_type"
android:text="#string/metric_unit_type"
android:onClick="onMetricRadioButtonClicked"/>
<RadioButton android:id="#+id/imperial_unit_type"
android:text="#string/imperial_unit_type"
android:onClick="onMetricRadioButtonClicked"/>
</RadioGroup>
You would need to maintain the View instance of view_gender and view_unit_type inside your class. onCreate is a good place to do it using findViewById.
protected void onCreate(Bundle savedInstanceState) {
view_gender = (RadioGroup) findViewById(R.id.gender_RadioGroup);
view_unit_type = (RadioGroup) findViewById(R.id.unit_type_RadioGroup);
}
public void onGenderRadioButtonClicked(View view) {
if(((RadioButton) view).isChecked())
chooseLayout(view, view_unit_type );
}
public void onMetricRadioButtonClicked(View view) {
if(((RadioButton) view).isChecked())
chooseLayout(view_gender, view);
}
public void chooseLayout(View View1, View View2){
if (View1.getId()==R.id.male && View2.getId()==R.id.metric_unit_type)
// show male metric type layout
else if (View1.getId()==R.id.male && View2.getId()==R.id.imperial_unit_type)
// show male imperial type layout
else if (View1.getId()==R.id.female && View2.getId()==R.id.metric_unit_type)
// show female metric type layout
else
// show female imperial type layout
}

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