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..
Related
image123(ImageView) works normal but when it comes to ONclickListener it does not work even after using different methods of Calling the listener.
I put func(),which contain findviewbyid of image123 (ImageView) just after SetContentView() and it works fine .OnclickListener of image123 does not works when func() is in OnClicklistener of Reset Button as Shown in the Code.
Problem:
How can i call the func() in reset button onclicklistener as well as in start at Oncreate() Activity?
It catch an exception shown in Log cat
- Exception at Onclick Listener" ,"java.lang.NullPointerException
public class MainActivity extends Activity {
ImageView image123;
int[] resultid=new int[25];
Button buttonExit;
Button buttonreset;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonreset=(Button) findViewById(R.id.button_reset);
buttonExit=(Button) findViewById(R.id.button_exit);
v1=(TextView)findViewById(R.id.name);
v2=(TextView)findViewById(R.id.fruit_count);
//--------------------------Exit Button---------------------------
buttonExit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
//*******************Exception comes here*********************
try{
image123.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d("Listner Called", "Listner Called");
}
});
}
catch(Exception e)
{
Log.d("Exception at onclickListener", e.toString());
}
buttonreset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
func();
}});
}
void func()
{
String as=null;
int resultid;
SecureRandom random=new SecureRandom();
image123=new ImageView(this);
as=("img"+1).toString();
resultid=getResources().getIdentifier(as, "id","com.example.selectiongame" );
Log.d(as, ""+resultid);
image123=(ImageView) findViewById(resultid);
as="drawable"+(random.nextInt(3)+1);
resultid = getResources().getIdentifier(as, "drawable", "com.example.selectiongame");
Log.d(as, ""+resultid);
image123.setImageResource(resultid);
}
Try creating an array of ResIDs and an array of ImageViews. Then do something like this instead of initializing them with findViewById()...
for(int i = 0; i < res_arr.length; i++)
{
images[i] = new ImageView(this);
images[i].setImageResource(res_arr[i]);
images[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Button_Clicked", "Button Clicked");
}
});
}
You must not findviewbyid() of an ImageView in some other function other than Oncreate(Bundle b) or Some Listener(e.g OnclickListener ,onselectionchange etc) . if you want to findviewbyid(...) of a view in a function other than Oncreate ,Atleast Call that function once after SetContentView() and other prerequisite Findviewbyid(...).
2.
In order to Refresh your Activity ,when you can not use function containing findviewbyid(...) of ImageView,like in my case, in body some button(e.g Refresh ,Reset) OnclickListner .You must write the following code
buttonreset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Bundle newBundle=new Bundle();
onCreate(newBundle);
//func(); >>We can not use this func() here if we are using it in Oncreate(...) in case of Array of ImageView
}});
}
For views other than Imageview ,Maybe Regular Line of Code work ...But in case of ImageView or Array of ImageView ....These things must be kept in mind and Simply Oncreate() must be used to Refresh.
I'm new to android development..
I have this code in my main class:
Button prevBtn, pauseBtn, nextBtn;
EditText counterTxt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_affirmations);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prevBtn = (Button)findViewById(R.id.prevBtn);
pauseBtn = (Button)findViewById(R.id.pauseBtn);
nextBtn = (Button)findViewById(R.id.nextBtn);
counterTxt = (EditText)findViewById(R.id.counterTxt);
prevBtn.setOnClickListener(new View.OnClickListener() {
int t = Integer.parseInt(counterTxt.getText().toString());
public void onClick(View v) {
counterTxt.setText(String.valueOf(t-1));
}
});
nextBtn.setOnClickListener(new View.OnClickListener() {
int t = Integer.parseInt(counterTxt.getText().toString());
public void onClick(View v) {
counterTxt.setText(String.valueOf(t+1));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_affirmations, menu);
return true;
}
When I click "Previous", the text field value becomes 19.
When I click "Next", the text field value becomes 21.
But it only displays these two values, nothing else, no matter if i click again. I want to subtract or add 1 whenever i click the appropriate buttons.
I think this happens because the event Listeners are inside onCreate() method? Any idea on how to make it update each time I click?
You need to move your parseInt inside your onClick:
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int t = Integer.parseInt(counterTxt.getText().toString());
counterTxt.setText(String.valueOf(t+1));
}
});
In both cases, t is defined as a member variable of the listener, and never changed. move it inside the onClick method instead, like this (in both cases):
public void onClick(View v) {
int t = Integer.parseInt(counterTxt.getText().toString());
counterTxt.setText(String.valueOf(t-1));
}
I have 100 buttons (from button000 to button 999). Is there any way to setOnClick for all of them? Because all button have the same function.
Thanks in advance.
If your buttons are inside a layout then do like this.
int childcount = ll.getChildCount();
for (int i=0; i < childcount; i++){
View v = ll.getChildAt(i);
v.setOnCLickListener(this);
}
Buddy try this way
import android.view.View.OnClickListener;
public class MyActivity extends Activity implements OnClickListener {
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonA = (Button) findViewById(R.id.buttonA);
buttonA.setOnClickListener(this);
Button buttonB = (Button) findViewById(R.id.buttonB);
buttonB.setOnClickListener(this);
}
//etc... etc...
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonA:
// do something
break;
case R.id.buttonB:
// do something else
break;
}
}
At right now I can say easiest way in
use button000.setOnclicklistener(this);
:
:
button999.setOnclicklistener(this);
and implement Onclicklistener in this current class....
if you are sure that it's the best way for your app to create 1000 buttons, then it will be something like this:
Button [] my_button=new Button[1000];
LinearLayout ll=(LinearLayout)findViewById(R.id.mylayout);
for (int i=0;i<1000;i++){
my_button[i]=new Button(this);
my_button[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
my_button[i].setText("button "+i);
ll.addView(my_button[i]);
my_button[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
////click event
}
});
}
Just add your buttons in an array and
Just loop the buttons and on a listener you can call the following block of code:
for (int i=0; i < buttonArray.length; ++i){
buttonArray[i].onClick(this);
}
there are two methods one is you can set onClick in xml layout file by onClick method you can define the method, that should be invoked when button is clicked. This method is appropriate when you define buttons in xml.
If you are adding buttons in Activity, and if you are adding in a loop then you can do as
for(int i=0; i<100; i++)
{
//Create and Add button
btn.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
//Operations
}
});
}
Best way to make Button Dynamically like
Integer[] button_Ids = {R.id.btn000,R.id.btn001...............,R.id.btn999};
for(int i=0;i<100;i++)
{
Button btn = (Button)findViewById(button_ids[i]);
btn.setOnClickListner(this);
}
#Override
public void onClick(View v)
{
Toast.make(getApplicationContext,"Hello",1000).show();
}
If all buttons have exactly same functionality then you can simple use
private OnClickListener mListenr=new OnClickListener(
#Override
public void onClick(View v) {
//Whatever you want
}
for(int i=0; i<100; i++)
{
mButton[i].setOnClickListener(mListenr);
}
you can refer this to see ways to implement listener.
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>
imgvw_back.setOnClickListener(this);
imgvw.setOnClickListener(this);
static id=10
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.back:
Log.v("back",""+id--);
break;
case R.id.forward:
Log.v("next",""+id++);
break;
}
}
i am using this kind of concept but mostly fire R.id.back part ,what can i do plz give solution for this problem...
The id may not be what you think it is, you could do something like this.
imgvw_back.setOnClickListener(this);
imgvw.setOnClickListener(this);
static id=10
#Override
public void onClick(View v)
{
if(v == imgvw_back)
{
Log.v("back",""+id--);
}
else if(v == imgvw)
{
Log.v("next",""+id++);
}
}
Use inline onClickListeners for each button.
imgvw_back.setOnClickListener(new onClickListener(){
#Override
public void onClick(View v){
Log.v("back", "")
}
});
Is imgvw your forward button? Just wondering, cause your back button is imgvw_back, would assume forward would be named accordingly imgvw_forward.
You're probably missing missing to set the clickListener to the forward button as well.