User Interface Layout Interaction
EventsEvent Handlers/Listeners Interacting with a user.
The root of GUI elements is the View class. UI elements such as Buttons Labels Editable text Images Etc derive from the View class. We define our app’s response to a click by implementing an instance of View.OnClickListener interface. Handling Clicks public class View{ … //nested class public interface OnClickListener { void onClick(View v); } … }
Click Handler idioms: 1. Have the class that owns the GUI element implement the OnClickListener interface. 2. Create an anonymous class that implements OnClickListener interface. 3. Create an anonymous class that implements OnClickListener interface.
public class PixFragment extends Fragment implements public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View v = inflater.inflate(R.layout.pix_frag_layout, container, false); ImageView mSplashView = (ImageView)v.findViewById(R.id.pix_view); mSplashView.setOnClickListener(this); return v; } public void onClick(View v){ // handle the click Log.d("PixFragment", "I was clicked"); } 1. Have the class that owns the GUI element implement the OnClickListener interface.
2 Create an anonymous class that implements OnClickListener interface. public class PixFragment extends Fragment{ private View.OnClickListener mSplashViewListener = new View.OnClickListener() public void onClick(View v) { // handle the click Log.d("PixFragment", "I was clicked"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View v = inflater.inflate(R.layout.pix_frag_layout, container, false); ImageView mSplashView = (ImageView)v.findViewById(R.id.pix_view); mSplashView.setOnClickListener(mSplashViewListener); return v; }
3 Create an anonymous class that implements OnClickListener interface. public class PixFragment extends Fragment implements public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View v = inflater.inflate(R.layout.pix_frag_layout, container, false); ImageView mSplashView = (ImageView)v.findViewById(R.id.pix_view); mSplashView.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ // handle the click Log.d("PixFragment", "I was clicked"); } }) ; return v; }
2. Create a standalone class that implements OnClickListener interface. import android.view.View.OnClickListener; public class PixFragment extends Fragment{{ public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View v = inflater.inflate(R.layout.pix_frag_layout, container, false); {... Button button = (Button)findViewById(R.id.corky); button.setOnClickListener(new MyClickListener()); … return v; }... //Inner class private class MyClickListener implements OnClickListener implements OnClickListener { public void onClick(View v) { // do something when the button is clicked }