android | multiple onclicklistener in dialog - android

Inside my Activity I start a simple dialog.
final Dialog myDialog = new Dialog(this);
myDialog.setContentView(R.layout.testing);
...
My testing.xml Layout consists of nothing but 10 ImageViews, id`s are '1' to '10'.
I want every ImageView to be clickable and to do something.
The define the onclick() methode in the .xml file isn`t working, as the methode can't be found when the dialog is viewed.
The only way I got it work is following: define 10 onclick-listeners:
ImageView img_1 = (ImageView) myDialog.findViewById(R.id.1);
ImageView img_2 = (ImageView) myDialog.findViewById(R.id.2);
...
img_1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
execute_funtion(1);
myDialog.cancel();
}
});
img_2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
execute_funtion(2);
myDialog.cancel();
}
});
...
However, that's really bad code, I have 10 times nearly the same lines.
So my question: How can I make that work with clean code?
I thought about a multiple onclicklistener (overwride the onClick() function and make a switch/case in the functions or something like that), but it's not working.
I'm happy about every idea!
Thanks
/EDIT
Here a snippet of the .xml file
<ImageView
android:id="#+id/1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:onClick="myFunction"
android:src="#drawable/ic_launcher" />

Make your Activity implement OnClickListener and then process the onClick event like below:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.img1:
...
break;
case R.id.img2:
...
break;
}
}

You should let your Activity/Fragment implement the OnClickListener.
When you do that you will have to override the onClick method in that particular activity/fragment.
Set the onClickListeners on the images as follows:
img_1.setOnClickListener(YourActivity.this);
Then in that onClick method you can put a switch case or an if else if case as follows
#Override
public void onClick(View v)
{
if(v==img_1) {
//do this
} else if(v==img_2) {
//do that
}...
}
or
#Override
public void onClick(View v)
{
switch (v.getId()) {
case img_1.getId(): // do this
break;
case img_2.getId(): // do that
break;
.
.
.
default : break;
}
}

Related

what is better way to organize onclicklistener? [duplicate]

This question already has answers here:
Multiple Buttons' OnClickListener() android
(11 answers)
Closed 7 years ago.
When you have many buttons in a view and all the button have listener. Your main activity gets dirty.
Anyone know how to organize listeners ?
Currently I used this way and implement onClickListener.
spotify =(Button)findViewById(R.id.spotifyBtn);
superDuoBtn = (Button) findViewById(R.id.superDuoBtn);
libraryBtn = (Button) findViewById(R.id.libraryBtn);
buildBiggerBtn = (Button) findViewById(R.id.buildItBiggerBtn);
capstoneBtn= (Button) findViewById(R.id.capstoneApp);
spotify.setOnClickListener(this);
superDuoBtn.setOnClickListener(this);
libraryBtn.setOnClickListener(this);
buildBiggerBtn.setOnClickListener(this);
capstoneBtn.setOnClickListener(this);
You could set the property:
android:onClick="buttonClicked"
in the xml file for each of those buttons, and use this in the java code:
public void buttonClicked(View view) {
if (view.getId() == R.id.button1) {
// button1 action
} else if (view.getId() == R.id.button2) {
//button2 action
} else if (view.getId() == R.id.button3){
//button3 action
}
}
You can implement onclicklistner for multiple buttons using swith case
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.firstButton:
// do your code
break;
case R.id.secButton:
// do your code
break;
case R.id.thirdButton:
// do your code
break;
......
default:
break;
}
}
Ya...It s the best way to use multiple onClickListener.
spotify =(Button)findViewById(R.id.spotifyBtn);
superDuoBtn = (Button) findViewById(R.id.superDuoBtn);
libraryBtn = (Button) findViewById(R.id.libraryBtn);
buildBiggerBtn = (Button) findViewById(R.id.buildItBiggerBtn);
capstoneBtn= (Button) findViewById(R.id.capstoneApp);
spotify.setOnClickListener(this);
superDuoBtn.setOnClickListener(this);
libraryBtn.setOnClickListener(this);
buildBiggerBtn.setOnClickListener(this);
capstoneBtn.setOnClickListener(this);
#Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.spotifyBtn:
intent = new Intent(this, SimpleSingleExample.class);
break;
case R.id.superDuoBtn:
intent = new Intent(this, CustomExample.class);
break;
case R.id.libraryBtn:
intent = new Intent(this, SequenceExample.class);
break;
case R.id.buildItBiggerBtn:
Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
break;
}
if(intent!=null){
startActivity(intent);
}
}
If you want better way than you have to use Android Annotations, its simple and useful, you can find here
Add those View object references to some type of list, iterate through it usin a for-each loop, then call the setOnClickListener on each element which will reduce those lines to just 2 lines for you.
ArrayList <View> list = new ArrayList <>(spotify,superDuoBtn,libraryBtn, buildBiggerBtn, capstoneBtn);
for (View view : list) {
view.setOnClickListener(this);
}
The most obvious example of alternative approaches to solving a single problem seems to be the various ways you can handle button clicks. As far as I know, there are four different ways to add listeners for handling button clicks. If you know of other ways, please post a comment and share them with us.
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"
>
<Button android:text="Inner Class (btn1)" android:id="#+id/Button01"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</Button>
<Button android:text="Anonymous Inner Class (btn2)"
android:id="#+id/Button02" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button android:text="Implementing an Interface (btn3)"
android:id="#+id/Button03" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button android:text="Calling From XML Layout (btn4)"
android:id="#+id/Button04" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="btn4Listener">
</Button>
</LinearLayout>
in MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Main extends Activity implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//method 1 - uses an inner class named btn1Listener...
Button btn1 = (Button)findViewById(R.id.Button01);
btn1.setOnClickListener(btn1Listener);
//method 2 - use an anonymous inner class as a listener...
Button btn2 = (Button)findViewById(R.id.Button02);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("You clicked btn2 - uses an anonymouse inner class");
}
});
//method 3 - note that this class implements
//the View.OnClickListener interface
//which means that we must implement the onClick()
//method (which you'll find below)..
Button btn3 = (Button)findViewById(R.id.Button03);
btn3.setOnClickListener(this);
//method 4 - look at the method btn4Listener() below
}
//here's the inner class used as a listener for btn1...
private View.OnClickListener btn1Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("You clicked btn1 - uses an inner class named btn1Listener");
}
};
//here's a method that you must have when your activity implements the
//View.OnClickListener interface...
#Override
public void onClick(View v) {
showToastMessage("you clicked on a btn3, which uses this Activity as the listener");
}
//here's the handler for btn4 (declared in the xml layout file)...
//note: this method only works with android 2.1 (api level 7), it must be public and
//must take a single parameter which is a View
public void btn4Listener(View v) {
showToastMessage("You clicked btn4 - listener was set up in the XML layout");
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}

Change the color of a view with a button click in android?

This is to create a greeting card application and here i have to change the background color of the view( which is the background of the card) when a button is clicked. When i click the button labeled red the view should change it's color to red. and so on. Can someone help me with this?
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.btn1:
layout= (FrameLayout) findViewById(R.id.laidout);
layout.setBackgroundColor(Color.RED);
break;
}
I don't think your myClickHandler will work, try this:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// your switch case etc...
}
});
You should write your code in onClick(View view) method instead of myClickHandler().And the id "btn1" should be the id name which you declared in your xml file.

android view id is not correct

I create a whole layout setup in XML then attempt to attach listeners to the buttons using findViewById(). The problem I am having now is that the View parameter I receive in the method does not contain the ID of the view I clicked: 830009633920 vs 2131099657.
Button btnNext = (Button)findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnNext) {
...
}
}
How about this:
Button btnNext = (Button)findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
#Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.btnNext:
...
break;
case R.id.foo:
...
break;
}
}
That should be working, so my only guess without seeing the rest of the code or layout is that you have set click handlers on two items that overlap.
If you plan on making an Android Library project switch like this will not work due to a recent change in the tool chain.
http://tools.android.com/tips/non-constant-fields
In general I find it is much simpler to use an anonymous class the handle clicks rather than a large single handler.
btnNext.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
...
}
});
You might try this approach just to debug that the item you expect to get the click is what you are pressing, to make sure you don't have layout issues.
Try skipping the IDs, and just compare the actually view object. so something like this:
#Override
public void onClick(View view) {
if (view.equals(btnNext)) {
...
}
}

how to make text view clickable in android?

is it possible in android to make text view clickable if yes then how ??and if not then what will be the way for make a label clickable??i want to implement a call activity using this
private void call() {
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+keywordxmlparsing.phone));
startActivity(callIntent);
} catch (ActivityNotFoundException activityException) {
Log.e("dialing-example", "Call failed", activityException);
}
}
thanks for ur responses in advance...
textView.setOnClickListener(new View.OnClickListener());
Have you tried this?
More easier directly in the XML : with clickable = true
<TextView
android:id="#+id/forgotPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="#string/forgotPassword"
android:onClick="forgotPassword"
android:clickable="true"
/>
We can also get click event on TextView same as Button & ImageView.
and method is also same for all View.
like as
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
First in your java file cast your TextView by xml id
TextView tv = (TextView)findViewById(R.Id.textView1);
then,
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Honestly, I found a flat button to work better for what I was doing with a RecyclerView:
<Button
android:id="#+id/btnFoo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/borderlessButtonStyle"/>
Source: https://stackoverflow.com/a/30884132/2328637
Then customizing the button to fit my layout and finally adding the following to my MainActivity.java under onCreate:
Button btnFoo = (Button) findViewById(R.id.btnFoo);
btnFoo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, FooActivity.class);
startActivity(intent);
}
});
Try this:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
In the xml for that TextView include the field
android:onClick="functionName"
Then in your java file associated with that xml include this function
public void functionName(View view){
// do your stuff
}
you can set a onclick listener to the texview like button.infact button inherits the properties from textview.
Though it was long ago when you asked your question. But I think that the right thing to attain what you wanted is to set TextView xml attribute android:autoLink. For example:
<TextView
...
android:autoLink="phone" />
Simply try this one:-
Implement View.OnClickListener, then simply apply switch case and define the id of your text view in the case and pass the intent.
example:-
#Override
public void onClick(View v) {
//TODO Auto-generated method stub
switch (v.getId()) {
case R.id.textView:
startActivity(new Intent(this,CalledClass.class));
break;
default:
break;
}
//here textView is id for the textView I chose.
TextView is also derived of View like- EditText,ListView etc.,so we can use
textView.setOnClickListener(new View.OnClickListener());

Variable OnClick Listener Android

Is there a way to have 1 onClick Lister for many buttons where I can toss a case statement to do things based on what buttons were clicked.
I know I can make 100 different listeners for 100 buttons but I have to think I can create some nifty variables to do it in less lines of code.
Button btn1, btn2;
public void onCreate(Bundle b)
{
// here you do normal things like assigning a
// content view to the activity, initiate buttons, etc.
// then you assign the same listener to both buttons
btn1.setOnClickListener(yourListener);
btn2.setOnClickListener(yourListener);
}
// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener yourListener = new View.OnClickListener(){
public void onClick (View v){
if( v == btn1 ){
// do something
}
elseif( v == btn1 ){
// do another thing
}
}
};
If you are using 1.6+ version of the SDK you can use android:onClick to set the onClick handler of a view. In your activity you must have a method with the following signature. The view is the view that was clicked.
void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
//do something fantastic;
break;
}
}
public class MainActivity extends Activity implements View.OnClickListener{
btnXXX.setOnClickListener(this);
public void onClick(View v) {
if (v.getId()==R.id.btnXXX){
dialog.show();
} else {
handleOtherViews(v);
}
}
Alternatively, you can specify the method to call in xml:
<Button android:id="#id/button" android:text="#string/button" android:onClick="someMethod" />

Categories

Resources