Saturday, March 2, 2013

Android Button Click

                                           ANDROID BUTTON CLICK

If you are developing android you always have to give response to button clicks. As there are lots of handling types of button clicks i would choose the type for the usage in code. For example you can define your Button in layout file xml as well as programmatic way in java. If you do not want to create new class and you do not want to deal with overriding functions you can write your function name into the xml file such as
In Layout Xml File

<Button
        android:id="@+id/writeToFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onclick = "writetofile"
        android:text="@string/writeTo" />

In Activity File
public void writetofile(View view){
 // View will be the clicked button
view.getVisibility();
}

I would choose this if i do not want to comply with complex code.

If i do not want to write into the xml file so i will write into the java file there are again 2 types.
Individual one is

Button button = (Button) findViewById(R.id.writeToFile);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//Handle your code
                        }
}

If you do not want to open unique function for each type of button click you will register for a handler which is the second type in java.

While in activity
button.setOnClickListener(this);
//inside activity you will create the function below
public void onClick(View view)
{  
switch (view.getId()){
                        case R.id.writeToTextFile:
Toast.makeText(view.getContext(), "You pressed to Write To File", Toast.LENGTH_SHORT).show();
break;
                }
         }

So third one is beneficial for the usage of code(less code and more efficient function)

No comments:

Post a Comment