How to toggle background image on button click? - android

I have this code:
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
button1.setBackgroundResource(R.drawable.detailpressed);
Chapter_sync.add(chapid);
}
What I am trying to do is toggle all the methods called in the following clicklistener.
Eg first time when I Click this button the setBackgroundResource(R.drawable.detailpressed) is called and on the next click same metod is called with different drawable.
Something like toggle button.
Someone good at this plz help?

you can take a variable
int i=0;
it will increase with every click.
if(i%2==0)
set one image
else
set another image

How about creating an array of the drawable's IDs and saving an index:
private final int[] myDrawables = {R.drawable.detailpressed, R.drawable.detailpressed1, ...};
//...
button1.setOnClickListener(new OnClickListener() {
int index = 0;
#Override
public void onClick(View v) {
button1.setBackgroundResource(myDrawables[index++ % myDrawables.length]);
Chapter_sync.add(chapid);
}
}

declare variable as
boolean isOddClicked = true;
And update your click listener as
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Do stuff here for chnaging background of button
if(isOddClicked) {
button1.setBackgroundResource(R.drawable.detailpressed);
isOddClicked = false;
} else {
button1.setBackgroundResource(R.drawable.detailpressed_SECOND_IMAGE);
isOddClicked = true;
}
//Do your task
Chapter_sync.add(chapid);
}
NOTE: If your requirement moves between two images then you can use toggle button and customize it. It will work for same as your requirement.

if xml as the following
<code>
<Button
android:id="#+id/btnListView"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#drawable/list_view"
android:onClick="switchToListView"
android:visibility="visible"
/>
<Button
android:id="#+id/btnGridView"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#drawable/grid_view"
android:onClick="switchToGridView"
android:visibility="gone"
/>
<code>
handling Code will be like
<code>
public void switchToListView(View view) {
(Button) findViewById(R.id.btnListView).setVisibility(View.GONE);
(Button) findViewById(R.id.btnGridView).setVisibility(View.VISIBLE);
}
public void switchToGridView(View view) {
(Button) findViewById(R.id.btnGridView).setVisibility(View.GONE);
(Button) findViewById(R.id.btnListView).setVisibility(View.VISIBLE);
}
</code>

Related

ImageView is not loading correctly

In my Activity I have one ImageView
XML Code:
<!-- FOTO LATERAL! -->
<ImageView
android:id="#+id/simbolo_raca"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<Button
android:id="#+id/button_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok. Seguinte Pergunta"
android:layout_gravity="right"
android:gravity="right"
android:paddingRight="30dip">
</LinearLayout>
This is the Activity:
public class QuestionarioActivityRaca extends Activity{
ImageView simbolo;
int position;
Button B_Save;
List<Drawable> List_imagens = new ArrayList<Drawable>();
#Override
public void onCreate(Bundle savedInstanceState) {
simbolo = (ImageView) findViewById(R.id.simbolo_raca);
B_Save = (Button) findViewById(R.id.button_save);
position = 0;
List_imagens.add(getResources().getDrawable(R.drawable.p1));
List_imagens.add(getResources().getDrawable(R.drawable.p2));
List_imagens.add(getResources().getDrawable(R.drawable.p3));
List_imagens.add(getResources().getDrawable(R.drawable.p4));
loadNewImage(position);
B_Save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
loadNewImage(position);
position++;
}
});
}
// I Use this method to load the Image
public loadNewImage(int Page)
{
new Thread(new Runnable(){
#Override
public void run(){
simbolo.post(new Runnable(){
#Override
public void run()
{
simbolo.setImageDrawable(List_imagens.get(Page));
}
});
}
}).start();
}
The first time I call this method, (position = 0) the image doesnt loads. After that, the image is loading correctly.
How I have to do to load the image the first time?
(I can not load the image in the XML using android:src="#drawable/x") because the image could be different anytime.
EDITED!
There are a number of issues with the code sample you posted.
like writing int with a capital I.
Int position;
Not sending in a parameter with your method in the onClick:
public void onClick(View v) {
loadNewImage();
}
And several more in both your XML and code.
Is there a spesific reason you want to run a new thread every time for this task?
If you really need a thread, you have to declare your int as final in the method.
However, you should get your desired result with the code-sample below.
You have to modify your onClick to send the appropriate int for whatever drawable you want to use.
Good luck.
public class testactivity extends ActionBarActivity {
ImageView simbolo;
int position;
Button B_Save;
List<Drawable> List_imagens = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testactivity);
simbolo = (ImageView) findViewById(R.id.simbolo_raca);
B_Save = (Button) findViewById(R.id.button_save);
position = 0;
List_imagens.add(getResources().getDrawable(R.drawable.ic_drawer));
List_imagens.add(getResources().getDrawable(R.drawable.ic_check));
List_imagens.add(getResources().getDrawable(R.drawable.ic_action_add_package));
List_imagens.add(getResources().getDrawable(R.drawable.ic_action_exception));
loadNewImage(position);
final Random rand = new Random();
B_Save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
loadNewImage(rand.nextInt(4));
}
});
}
public void loadNewImage(final int page)
{
simbolo.setImageDrawable(List_imagens.get(page));
}
}
first of all before the button gets clicked you call this function to load the initial image with loadNewImage(position); when the button is clicked you call this function loadNewImage(); i am guessing it works when the button is clicked because this loadNewImage(); method is ok and loadNewImage(int page); is not ok, because they are two different function.
Solving your problem if you want an integer object use Integer position or else go with int position and please let go of the thread. now your code will work

on click long implementation when onClick is already in XML?

I have actually read several answers to this but they are so different than the simple way I am implementing click responses that I am wondering if there is a way to add something simple to what I am doing to create an onLongClick responas.
Basically, all my XML code is written with statements like this:
android:onClick="onSync"
Then my Java has:
public void onSync(View v) {
...
Toast toast3=Toast.makeText(this, "Sync was pressed",Toast.LENGTH_SHORT);
toast3.show();
}
What I would like to do is have a different function that is called when the button gets a long press. Right now, a long press causes the same action as a short press.
Specifically, I would like to know how to interface to a routine such as this:
public void onSyncLong(View v) {
...
Toast toast3=Toast.makeText(this, "Long Sync was pressed",Toast.LENGTH_SHORT);
toast3.show();
}
I would certainly appreciate any help on this problem. It would be great if the reply told me what to do in the XML and in the Jave. Thanks so much.
----------------------------UPDATE------------------------
Here is my onCreate code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.start_meters);
textLL = (TextView)findViewById(R.id.textLL);
textTimer = (TextView)findViewById(R.id.textTimer);
textTimeToLine = (TextView)findViewById(R.id.textTimeToLine);
Button button = (Button) findViewById(R.id.button_sync);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return true;
}
});
}
And here is the button XML segment
<Button
android:id="#+id/buttonSync"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Gun/Sync"
android:onClick="onSync"
android:textSize="#dimen/font_small"
android:background="#drawable/round_button"
android:padding="3sp"
android:longClickable="true"/>
------------Final Update----------------
Here is the working code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.start_meters);
textLL = (TextView)findViewById(R.id.textLL);
textTimer = (TextView)findViewById(R.id.textTimer);
textTimeToLine = (TextView)findViewById(R.id.textTimeToLine);
Button button = (Button) findViewById(R.id.buttonSync);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
StartLine2.startTime = pTime + 1000*60*5;
return true;
}
});
}
You can't do this via XML. Instead, use:
Button button = (Button) findViewById(R.id.<your_id>);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return true;
}
});
Make sure this code comes after setContentView() has been called.
Also, make sure that the android:longClickable property is set to true.
In your XML, the ID is set to buttonSync, while in the Java code you're using button_sync. This is the reason for your NullPointerException, as you don't have a button called button_sync.
public class GameScoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Log.v("TTT", "GameScoreFragment.OnCreateView()");
View viewScore = inflater.inflate(R.layout.gamescorelayout, container, false);
// set onLongClick listeners for both buttons
// when player long presses any of the two buttons, scores are reset
Button tempButton = (Button) viewScore.findViewById(R.id.id_button_pone_score);
tempButton.setOnLongClickListener( mLongListener );
tempButton = (Button) viewScore.findViewById(R.id.id_button_ptwo_score);
tempButton.setOnLongClickListener( mLongListener );
return viewScore;
}
// define a variable mLongListener to hold the listener code
// and then use mLongListener to set the listener
// if we don't define the variable, then we will have to write the listener code at two places (once for each button)
private View.OnLongClickListener mLongListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View pView) {
//reset player scores
GameFragment tempGameFragment = (GameFragment) getFragmentManager().findFragmentById(R.id.id_gamefragment);
if (tempGameFragment != null)
tempGameFragment.resetPlayersScore(false);
return true;
}
};
}

One button used for two Action

Can any one tell me? how can i use the same button for two Action?
Like em using one button in my activity that calculate some values and after calculating the when i again press same button then reset the all fields. Like in this Application
http://www.craziness.com/games/play-love-tester/ when i test the love by pressing the button
then i again press the same button then all fields reset.
what should i use in my activity for the above problem?
You can create a global variable which indicates the state of the program and then change this value when needed. In the OnClickListener of your Button you create an if statement which checks this variable and does the needed things for the associated value.
Example:
public class MainActivity extends Activity {
private int state = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (state == 0) {
// State 1
}
else if (state == 1) {
// State 2
}
else {
// Default state
}
}
});
// Rest of your code including state changing part
}
}
You can do it by changing the button text.
If you do not want that someone sees the text change. Test (example "click" and the other state "click " (1 blank at the end) or another solution.
....
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// todo: check for expected instance (Button)
Button btc = (Button)v;
String bText = btc.getText().toString();
if (bText == "open") {
btc.setText("close");
}
else if (bText == "close") {
btc.setText("open");
}
}
[...]
You can do so by using a toggle button.
In your xml file add a toggle button
<ToggleButton
android:id="#+id/tbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textOff="Reset"
android:textOn="Calculation"
android:background="#drawable/icon"/>
Java file
public class Reviews extends Activity implements OnClickListener {
private ToggleButton tbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tbtn = (ToggleButton) findViewById(R.id.tbtn);
tbtn.setOnClickListener(this);
public void onClick(View view) {
if (tbtn.isChecked()) {
//calculate the result
}
else {
//Reset your global calculation variable;
}
}
}
}

how to set onclicklistener to items in current page?

I have an application where i want to add onclicklistener to my individual items in pager.
Below is my screen shot . please some one tell me how to add onclicklistener to individual image in this current page .
Thanks
below is my code for pager view.
here when 1st time run the app initialize the every view page, when i try to click on image it return only last image info. But i want the current image info.
scroller = ((Pager)findViewById(R.id.scrollView));
indicator = ((PageIndicator)findViewById(R.id.indicator));
indicator.setPager(scroller);
// Pager pager = new Pager(this, attrs)
//indicator.getActivePage();
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View pageView = null;
for (int i = 0; i < NUM_PAGES; i++) {
pageView = layoutInflater.inflate(R.layout.page, null);
// ((TextView) pageView.findViewById(R.id.pageText)).setText("Page " + (i+1));
c=4*i;
imageView1 = (ImageView) pageView.findViewById(R.id.imageView1);
imageView1.setImageResource(icons[c]);
imageView2 = (ImageView) pageView.findViewById(R.id.imageView2);
imageView2.setImageResource(icons[c+1]);
imageView3 = (ImageView) pageView.findViewById(R.id.imageView3);
imageView3.setImageResource(icons[c+2]);
imageView4 = (ImageView) pageView.findViewById(R.id.imageView4);
imageView4.setImageResource(icons[c+3]);
// pageView.setBackgroundColor(COLORS[i % COLORS.length]);
imageView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("helo i clicked==>"+c);
}
});
imageView2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("helo i clicked==>"+c);
}
});
imageView3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("helo i clicked==>"+c);
}
});
imageView4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("helo i clicked==>"+c);
}
});
scroller.addPage(pageView);
}
It seem to be you didn't read information available at android developers.
Use below code to add onClickListener for images. I don't know whether you are using ImageView or ImageButton. I took ImageView.
ImageView iv = new ImageView(/**Context you have to pass**/);
iv.setOnClickListener(new View.OnClickListener) {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// do whatever you want
}
});
I hope it may help you.
set this on your images..or button
in the xml such that
<Button [...]
android:onClick: "onClick" [...]
/>
"onClick": name this whatever you want your method name that handles clicks to be
This can be done by assigning onClickListeners to Image Buttons. You can use Image buttons to display these images and set onClickListeners on them. Perhaps something like this can help?
ImageButton button = (ImageButton) findViewById(R.id.imageButton1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Do your stuff here
}
});
If you use ImageView then set the property OnClick to true.

Android onClick method

I have two onclick method in android project
clr=(Button)findViewById(R.id.Button01);
clr.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tv1.setText("CLR");
et1.setText("");
refrigerant = "";
pres = "";
temperature = "";
superheat_oda = 0;
sub_cool = 0;
}
});
And i have onther onClick method in which i have to call that method directly
prs=(Button)findViewById(R.id.Button02);
prs.setOnClickListener(new OnClickListener() {
----- I have to call that method---
}
});
Is there Any Solution for this?
You want to call the first onClick from the second? Just extract the contents of your first onClick in a separate method and call that method from each onClick.
Edit: As per st0le's comment, you can do what you want by calling clr.performClick(). (Didn't know that.) Still, extracting it into a separate method seems cleaner.
you can do something like this in the XML file
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="some_function" />
and put this function in the Java file
public void some_function(View view) {
// stuff...
}
and put the some_function in both "onClick"s
You should turn to use the simplest way that I always do as below:
#Override
public void onCreate(Bundle savedInstanceState) {
button1.setOnClickListener(onClickListener);
button2.setOnClickListener(onClickListener);
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.button1:
//DO something
break;
case R.id.button2:
//DO something
break;
}
}
};
I would recommend to use the same OnClickListener for both buttons if both buttons really have to do the same thing:
OnClickListener l=new OnClickListener() {
public void onClick(View v) {
tv1.setText("CLR");
et1.setText("");
refrigerant = "";
pres = "";
temperature = "";
superheat_oda = 0;
sub_cool = 0;
}
};
clr=(Button)findViewById(R.id.Button01);
clr.setOnClickListener(l);
prs=(Button)findViewById(R.id.Button02);
prs.setOnClickListener(l);
or if its not exactly the same you could access the listener method by l.onClick(null); manually..

Categories

Resources