public class UnitConverterActivity extends Activity implements OnTouchListener {
/** Called when the activity is first created. */
LinearLayout mLinearLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLinearLayout = new LinearLayout(this);
ImageView i = new ImageView(this);
i.setImageResource(R.drawable.mainmenu);
//i.setAdjustViewBounds(false);
i.setScaleType(ScaleType.FIT_XY);
i.setLay开发者_如何学CoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mLinearLayout.addView(i);
setContentView(mLinearLayout);
//setContentView(R.layout.main);
}
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
}
I have used the above method to load an image for the main menu I am trying to create. The image has four areas and each will be used to call a particular function of the app. Now I am trying to implement touch interface on those areas. I know how to define the range of pixels for that purpose but I am at loss on how to implement OnTouchListner on the image. Please help me in this regard.
If your image was split into four rectangular quarters (say)
then in onCreate have:
i.setOnTouchListener(this);
and for your listener, something like this (illustrates the principle only):
@Override
public boolean onTouch(View v, MotionEvent mev) {
int width = v.getWidth();
int height = v.getHeight();
float x = mev.getX();
float y = mev.getY();
String msg;
if (x < width / 2) {
if (y < height / 2)
msg = "Top left quarter";
else
msg = "Bottom left quarter";
} else {
if (y < height / 2)
msg = "Top right quarter";
else
msg = "Bottom right quarter";
}
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
return false;
}
Just put this code in onCreate().
i.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//your code
}
}
精彩评论