Frage

So I have been developing in Android for quite some time and I am natively a .Net developer. The problem I am facing is that my code looks awful, and I really dislike the way that Java\Android not sure which, makes click events appear in code. In this example below I have a List View with a click event.

list_view.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // TODO Auto-generated method stub

        }
    });

In .Net I would have set my click event in my Initialize Components method and then implemented it in my main code page. How do I tell android to use a click event method below in my code instead of referencing it right there. Maybe something like this?

list_view.setOnItemClickListener(onItemClick());

Later on in my code page.

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }
});

All in all I am just looking for a cleaner approach to wiring my events up to my controls so I can read the code better. It is a struggle moving to Java and Android when originally being a .Net developer.

Thanks!

Edit

Thank you for the answer below I posted my work here.

list_view.setOnItemClickListener(list_view_onItemClickListener);


//below in my code
private OnItemClickListener  list_view_onItemClickListener = new OnItemClickListener (){
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }

};
War es hilfreich?

Lösung

you can try this!

Andere Tipps

you may like or not but what approach i found best for me is for example this is your layout.xml

<Button1 android:id="@+id/btn1"  android:onClick="btnHandle">

</Button1>

<Button2 android:id="@+id/btn2 android:onClick="btnHandle">

</Button2>

and in your activity.Java

public void btnHandle(View v)
{
  if(v.getId()==R.id.btn1){


}else if(v.getId()==R.id.btn2){

}

by this approach you dont have to implement any interface and even if you change your Button view to ImageView still you dont have to do any thing in code. but in case of setOnClickListener you have to change your instance variable type from Button to ImageView. }

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top