So , I was not making my self clear. I'm having a little trouble trying to get a button index from a matrix.
I have this matrix bt[4][4], and each button has a value like this :
btn11 = bt[0][0].
Now what I want to do is, whenever I click on a Button, I get it´s "cordinates".
Ex: Bt11 would give [0] and [0] .
Now the problems that I'm having:
I've set listeners to each button, but I can't implement a "onClick" method.
Whenever I try to implement here "public class easy extends Activity" I get an error message.
Second problem, I don't know to get the cordinates from bt[x][y].
To sum it up. I want to set a onClick method so every time you click on a button you get it's [x][y] cordinates.
Here's my code:
public class easy extends Activity { //Can't implement OnClick Listener
Button bt[][] = new Button[4][4];
Button up;
Button down;
Button left;
Button right;
int listaTroca[] = new int[10]; // lista pra receber os valores de retorno da logica
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy);
//Linha 1
bt[0][0] = (Button) findViewById(R.id.bt11);
bt[0][0].setOnClickListener((View.OnClickListener) this);
bt[0][1] = (Button) findViewById(R.id.bt12);
bt[0][1].setOnClickListener((View.OnClickListener) this);
bt[0][2] = (Button) findViewById(R.id.bt13);
bt[0][2].setOnClickListener((View.OnClickListener) this);
bt[0][3] = (Button) findViewById(R.id.bt14);
bt[0][3].setOnClickListener((View.OnClickListener) this);
//--------------------- Linha 2
bt[1][0] = (Button) findViewById(R.id.bt21);
bt[1][0].setOnClickListener((View.OnClickListener) this);
bt[1][1] = (Button) findViewById(R.id.bt22);
bt[1][1].setOnClickListener((View.OnClickListener) this);
bt[1][2] = (Button) findViewById(R.id.bt23);
bt[1][2].setOnClickListener((View.OnClickListener) this);
bt[1][3] = (Button) findViewById(R.id.bt24);
bt[1][3].setOnClickListener((View.OnClickListener) this);
//------------------------Linha 3
bt[2][0] = (Button) findViewById(R.id.bt31);
bt[2][0].setOnClickListener((View.OnClickListener) this);
bt[2][1] = (Button) findViewById(R.id.bt32);
bt[2][1].setOnClickListener((View.OnClickListener) this);
bt[2][2] = (Button) findViewById(R.id.bt33);
bt[2][2].setOnClickListener((View.OnClickListener) this);
bt[2][3] = (Button) findViewById(R.id.bt34);
bt[2][3].setOnClickListener((View.OnClickListener) this);
//---------------------Linha 4
bt[3][0] = (Button) findViewById(R.id.bt41);
bt[3][0].setOnClickListener((View.OnClickListener) this);
bt[3][1] = (Button) findViewById(R.id.bt42);
bt[3][1].setOnClickListener((View.OnClickListener) this);
bt[3][2] = (Button) findViewById(R.id.bt43);
bt[3][2].setOnClickListener((View.OnClickListener) this);
bt[3][3] = (Button) findViewById(R.id.bt44);
bt[3][3].setOnClickListener((View.OnClickListener) this);
//----------------------FIM DECLARAÇÃO + OUVIDOS
listaTroca = Logic.Logic_main(1,1,1);
}
}
I'm not completely sure what your question is here, but from what i understand you want a View.OnClickListener() on each button, and when the button is being clicked you want to do something right?
EDITED: I've edited the answer as the question was clarified in the comments below.
What you want to do, is simply iterate your bt[][] to find the right button, like so:
public class Easy extends Activity {
Button[][] bt = new Button[4][4];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy);
//Linha 1
bt[0][0] = (Button) findViewById(R.id.bt11);
bt[0][0].setOnClickListener(mOnClickListener);
bt[0][1] = (Button) findViewById(R.id.bt12);
bt[0][1].setOnClickListener(mOnClickListener);
// ADD YOUR OTHER findViewByID
}
View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ButtonCoordinate bc = getButtonCoordinate(v);
if (bc != null) {
// You now have your button, and the coordinates
Log.d("Easy", "Button.position[ x:" + bc.x + ", y:" + bc.y + " ]");
}
}
};
private ButtonCoordinate getButtonCoordinate(View v) {
for (int x = 0 ; x < bt.length ; x++ ) {
for (int y = 0 ; y < bt[x].length ; y++) {
Button b = bt[x][y];
if (v == b) {
return new ButtonCoordinate(x, y, b);
}
}
}
return null;
}
public static class ButtonCoordinate {
public final int x;
public final int y;
public final Button button;
public ButtonCoordinate(int x, int y, Button button) {
this.x = x;
this.y = y;
this.button = button;
}
}
}
you just need to call getButtonCoordinate(View) which will return a ButtonCoordinate containing the Button and it's x and y coordinates in the bt[][]
Related
I want to make button which will call two function on click I am using this code currently but when I click it on 3rd time nothing happens and I want to do vice versa like when user click on button 3rd time it will call count 1 again.. this code is currently I am using
#Override
public void onClick(View v) {
clickcount=clickcount+1;
if(clickcount==1)
{
Random i = new Random ();
int c= i.nextInt(7-1) + 1;
bck.setBackgroundColor(Color.BLACK);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.WHITE);
}
else
{
Random i = new Random ();
int c= i.nextInt(7-1) + 1;
bck.setBackgroundColor(Color.WHITE);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.BLACK);
}
}
Hello mate Please do like this
clickcount=0;
#Override
public void onClick(View v) {
clickcount = clickcount + 1;
if(clickcount%2 == 1) {
Random i = new Random ();
int c = i.nextInt(7 - 1) + 1;
bck.setBackgroundColor(Color.BLACK);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.WHITE);
} else {
Random i = new Random ();
int c = i.nextInt(7 - 1) + 1;
bck.setBackgroundColor(Color.WHITE);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.BLACK);
}
}
Another solution with boolean:
boolean check = true;
#Override
public void onClick(View v) {
Random i = new Random ();
TextView textresult = (TextView) findViewById(R.id.textView);
int c= i.nextInt(7-1) + 1;
bck.setBackgroundColor(check ? Color.BLACK : Color.WHITE);
textresult.setTextColor(check ? Color.WHITE : Color.BLACK);
check = !check;
}
Or if you want two functions:
boolean check = true;
#Override
public void onClick(View v) {
if(check) {
// first function
} else {
// second function
}
check = !check;
}
Hello as the title state I'm trying to setup a next and previous buttons but I'm still new at coding so this has me a little confused.
I tried to use if statements with an enum within a single button but it defaults to last if statement when the event is handled here's the code-
private enum EVENT{
pe1, pe2, pe3, pe4;
}
EVENT currentEvent = EVENT.pe1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentEvent==EVENT.pe1) {
olText.setText("PE1");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe2;
}
if (currentEvent==EVENT.pe2){
olText.setText("PE2");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe3;
}
}
});
}
I tried to use the enumerator to assign a number to each if statement so when the user hit previous it would subtract and when they hit next it would add, each number would have some text or image within its if statement but as I said it defaults to the last if statement- Any help is much appreciated.
How about this?
int eventNum = 0;
int maxEvents = XXX;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
prevBtn = (Button) findViewById(R.id.prevBtn);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
setEventData(true);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(prevBtn) && eventNum > 0) {
eventNum--;
setEventData(false);
return;
}
if(v.equals(nextBtn) && eventNum < maxEvents - 1) {
eventNum++;
setEventData(true);
return;
}
}
}
nextBtn.setOnClickListener(listener);
prevBtn.setOnClickListener(listener);
}
private void setEventData(boolean animLeft) {
olText.setText("PE" + (eventNum + 1));
if(animLeft) {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
} else {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_right));
}
}
You'll want to create a class variable that keeps track of which text your TextView is showing. So in the following example, I create a list of Strings that I just store in a String array. Then I create an iterator variable which stores which String from the list I'm currently viewing in the TextView. Every time you click the previous or next button, you simply store your current state in the iterator variable so you can recall it the next time a click event comes in.
String[] labels = {"one", "two", "three", "four"};
int currentView = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onPreviousButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView--; //decrement our iterator
if(currentView < 0) currentView = 0; //check to make sure we didn't go below zero
textView.setText(labels[currentView]);
}
public void onNextButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView++; //increment our iterator
if(currentView > labels.length-1) currentView = labels.length-1; //check to make sure we didn't go outside the array
textView.setText(labels[currentView]);
}
Every time an user click on the button it has to show "John - Sue" or "Sue - John".
I tried with this code:
public class MyActivity extends Activity {
ArrayList<String> names = new ArrayList<String>();
int p1, p2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
names.add("John");
names.add("Sue");
Button b = (Button) findViewById(R.id.mybutton);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p1 = (int)Math.random();
if (p1 == 0)
p2 = 1;
else
p2 = 0;
String msg = names.get(p1) + " - " + names.get(p2);
AlertDialog msgbox = new AlertDialog.Builder(About.this).setTitle("Click here").setMessage(msg).create();
//msgbox.setPositiveButton("OK", null);
msgbox.setCancelable(true);
msgbox.show();
TextView textView = (TextView) msgbox.findViewById(android.R.id.message);
textView.setTextSize(16);
}
});
}
}
But i get always the same order, even i close and run again the app. How to do that?
If you want shuffle list:
Collections.shuffle(names)
If you want random int between 0 or 1 (nextInt(int) javadoc):
Random random = new Random();
int randomInt = random.nextInt(2);
Math.random() returns a number between 0 and 1. So when you cast it to int it will always be 0.
Try this:
p1 = (int)(Math.random()*2);
It happens because
p1 = (int)Math.random();
always gives you zero.
I am a beginner Android developer and I have a runtime error in my code: when I want to run it in a emulator or a device it show "force close" massage. My log is here:
http://upir.ir/934/1_5e07a.jpg
My Java code:
public class Third extends Activity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button d = (Button) findViewById(R.id.btn4);
d.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog();
}
});
}
public void dialog(){
final Dialog dialog = new Dialog(Third.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("واحد عدد وارد شده را انتخاب کنید");
dialog.show();
RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.rg);
final RadioButton rb1 = (RadioButton) dialog.findViewById(R.id.rb1);
final RadioButton rb2 = (RadioButton) dialog.findViewById(R.id.rb2);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
if(rb1.isChecked()) {
dialog.dismiss();
Button t = (Button)findViewById(R.id.btn5);
t.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EditText ft1 = (EditText)findViewById(R.id.f3);
TextView foot = (TextView)findViewById(R.id.foot);
TextView mile = (TextView)findViewById(R.id.mile);
TextView inch = (TextView)findViewById(R.id.inch);
TextView yard = (TextView)findViewById(R.id.yard);
TextView mm = (TextView)findViewById(R.id.millymeter);
TextView dm = (TextView)findViewById(R.id.decimeter);
TextView mim = (TextView)findViewById(R.id.micrometer);
TextView nm = (TextView)findViewById(R.id.nanometer);
TextView hand = (TextView)findViewById(R.id.hand);
TextView iron = (TextView)findViewById(R.id.iron);
TextView point = (TextView)findViewById(R.id.point);
if(ft1.getText().toString().length() == 0 ){return;}
int first = Integer.parseInt(ft1.getText().toString());
double equal = first *0.0328;
DecimalFormat formatf = new DecimalFormat("#.####");
String x = formatf.format(equal)+" فوت";
foot.setText(x);
first = Integer.parseInt(ft1.getText().toString());
equal = first * 0.000005;
DecimalFormat formatm = new DecimalFormat("#.####");
x = formatm .format(equal)+"مایل";
mile.setText(x);
equal = first * 0.393;
DecimalFormat formati = new DecimalFormat("#.####");
x = formati.format(equal)+"اینچ";
inch.setText(x);
equal = first * 0.0109;
DecimalFormat formaty = new DecimalFormat("#.#####");
x = formaty.format(equal)+"یارد";
yard.setText(x);
equal = first / 10;
DecimalFormat formatmi = new DecimalFormat("#.##");
x = formatmi.format(equal)+"دسی متر";
dm.setText(x);
int equalmm = first * 10;
x = equalmm+"میلی متر";
mm.setText(x);
int equalm = first * 10000;
x = equalm+"میکرو متر";
mim.setText(x);
int equaln = first * 10000000;
x = equaln + "نانو متر";
nm.setText(x);
equal = first * 0.098;
DecimalFormat formath = new DecimalFormat("#####.#####");
x = formath.format(equal)+"هَند";
hand.setText(x);
equal = first * 19;
x = equal+"آیرون";
iron.setText(x);
equal = first * 28;
x = equal+"پوینت";
point.setText(x);
}
});
}
You need to inflate your activity with a layout resource first before you can use the findViewById() method to retrieve views. If there's no layout, then there are no views which could possibly be found.
You are missing an important part. You need to add a view to your Activity in order to find the elements of that view like the Button you are trying to instantiate.
In your OnCreate method add this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.the_xml_file); //Here add the xml file with the view you want to show
Button d = (Button) findViewById(R.id.btn4);
d.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog();
}
});
}
After your super.onCreate(savedInstanceState); are you setting the content view?
e.g.
setContentView(R.layout.nameofxmlfilehere);
There are a set of buttons, I want to get the result:
When I click one of them, first I divide them into two parts: the clicked one and the others. I'm trying to set different color or alpha value to different them.
Now I use setAlpha, but when I change the value from 0 to 255, it works, but when I change the value from 255 to 0 , it doesnot work. I don't know why.
Maybe after I invoke the methodButton.setAlpha(), I need invoke another method?
my code:
public class MainActivity extends Activity {
// button alpha value: minimize value
public static int BUTTON_ALPHA_MIN = 0;
// button alpha value: maximize value
public static int BUTTON_ALPHA_MAX = 255;
private LinearLayout centerRegion;
private LinearLayout bottomRegion;
private Button btnCheckIn;
private Button btnReview;
private Button btnMyCircles;
private Button btnSettings;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// get all the widgets
getAllWidgets();
// set buttons click response function
btnCheckIn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
centerRegion.setBackgroundColor(android.graphics.Color.RED);
btnReview.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnMyCircles.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnSettings.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnCheckIn.getBackground().setAlpha(BUTTON_ALPHA_MAX);
}
});
btnReview.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
centerRegion.setBackgroundColor(android.graphics.Color.BLUE);
btnCheckIn.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnMyCircles.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnSettings.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnReview.getBackground().setAlpha(BUTTON_ALPHA_MAX);
}
});
btnMyCircles.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
centerRegion.setBackgroundColor(android.graphics.Color.YELLOW);
btnCheckIn.getBackground().setAlpha(BUTTON_ALPHA_MAX);
btnReview.getBackground().setAlpha(BUTTON_ALPHA_MAX);
btnSettings.getBackground().setAlpha(BUTTON_ALPHA_MAX);
v.getBackground().setAlpha(BUTTON_ALPHA_MIN);
}
});
btnSettings.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
centerRegion.setBackgroundColor(android.graphics.Color.MAGENTA);
btnCheckIn.getBackground().setAlpha(BUTTON_ALPHA_MAX);
btnReview.getBackground().setAlpha(BUTTON_ALPHA_MAX);
btnMyCircles.getBackground().setAlpha(BUTTON_ALPHA_MAX);
v.getBackground().setAlpha(BUTTON_ALPHA_MIN);
}
});
}
/**
* get all the widgets
*/
public void getAllWidgets() {
this.centerRegion = (LinearLayout) this.findViewById(R.id.center_region);
this.bottomRegion = (LinearLayout) this.findViewById(R.id.bottom_region);
this.btnCheckIn = (Button) this.findViewById(R.id.button_check_in);
this.btnReview = (Button) this.findViewById(R.id.button_review);
this.btnMyCircles = (Button) this.findViewById(R.id.button_my_circles);
this.btnSettings = (Button) this.findViewById(R.id.button_setting);
}
}
Using AlphaAnimation should work; verified on my device.
public class Test extends Activity implements OnClickListener {
private AlphaAnimation alphaDown;
private AlphaAnimation alphaUp;
private Button b1;
private Button b2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout ll = (LinearLayout) findViewById(R.id.linear_layout);
b1 = new Button(this);
b1.setText("Button 1");
b1.setOnClickListener(this);
ll.addView(b1);
b2 = new Button(this);
b2.setText("Button 2");
b2.setOnClickListener(this);
ll.addView(b2);
alphaDown = new AlphaAnimation(1.0f, 0.3f);
alphaUp = new AlphaAnimation(0.3f, 1.0f);
alphaDown.setDuration(1000);
alphaUp.setDuration(1000);
alphaDown.setFillAfter(true);
alphaUp.setFillAfter(true);
}
public void onClick(View v) {
if (v == b1) {
b1.startAnimation(alphaUp);
b2.startAnimation(alphaDown);
} else {
b1.startAnimation(alphaDown);
b2.startAnimation(alphaUp);
}
}
}
The key is calling setFillAfter(true) so that the alpha change persists.
Thanks for the question and the answer. This really helped me out.
For my solution, I needed to set the alpha of a button without seeing any animation effect, but the button.setAlpha(x) was failing sporadically. Using animations instead did the trick, but I had to set the duration to zero to get the automatic effect.
alphaDown = new AlphaAnimation(1.0f, 0.3f);
alphaUp = new AlphaAnimation(0.3f, 1.0f);
alphaDown.setDuration(0);
alphaUp.setDuration(0);
alphaDown.setFillAfter(true);
alphaUp.setFillAfter(true);
I use this for player controls in a media application, so I had something like this:
boolean bInitPrevEnabled = m_btPrev.isEnabled();
boolean bInitNextEnabled = m_btNext.isEnabled();
boolean bInitPlayEnabled = m_btPlay.isEnabled();
m_btPrev.setEnabled(true);
m_btNext.setEnabled(true);
m_btPlay.setEnabled(true);
// Process enabling of the specific buttons depending on the state
if (bInitPrevEnabled != m_btPrev.isEnabled())
m_btPrev.startAnimation((m_btPrev.isEnabled()) ? alphaUp : alphaDown);
if (bInitNextEnabled != m_btNext.isEnabled())
m_btNext.startAnimation((m_btNext.isEnabled()) ? alphaUp : alphaDown);
if (bInitPlayEnabled != m_btPlay.isEnabled())
m_btPlay.startAnimation((m_btPlay.isEnabled()) ? alphaUp : alphaDown);
Button btn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.main_btn);
Drawable d = getResources().getDrawable(R.drawable.imagen);
d.setAlpha(60);
btn.setBackgroundDrawable(d);
}
This works for me :)
public void setAlpha (int alpha) - deprecated
public void setAlpha (float alpha) (0f < alpha < 1f)
Added in API level 11