Some element has default drawable that automatically change on press, focus, selected ,etc like Button, CheckBox, RadioButton. etc.
But some element has no default drawable or background like TextView, LinearLayout, RelativeLayout ,etc but we can also apply the same effect on element click. For example, we want to change TextView background color on click to notify the users they have been clicked the TextView.
Also the advantage of creating our custom StateListDrawable is we can control the look and feel of our application in different android version. It will look at is even the application installed in different device when different android version.
Below is the very simple code snippet on how to apply StateLisDrawable on TextView.
import android.app.Activity; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.StateListDrawable; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.RelativeLayout; import android.widget.Toast; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener{ RelativeLayout contentView; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); contentView = new RelativeLayout(this); // CREATE OUR CUSTOM STATE LIST DRAWABLE StateListDrawable drawable = new StateListDrawable(); // ON PRESS/CLICK BACKGROUND drawable.addState(new int[]{android.R.attr.state_pressed},new ColorDrawable(Color.RED)); // DEFAULT BACKGROUND drawable.addState(new int[]{}, new ColorDrawable(Color.GREEN)); // CREATE OUR PARAM RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.CENTER_IN_PARENT); // CREATE OUR TEXTVIEW textView = new TextView(this); textView.setText("Click Me"); textView.setLayoutParams(params); // SET STATELISTDRAWABLE AS BACKGROUND textView.setBackgroundDrawable(drawable); textView.setPadding(50, 50, 50, 50); // SET CLICK LISTENER textView.setOnClickListener(this); contentView.addView(textView); setContentView(contentView); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show(); } }
In this example we just used background color to set the background of our view for simplicity but we can also apply image from resources or even image from sdcard.
Hope it help in android beginner programmer like me.
That's all !!!
No comments:
Post a Comment