package com.example.test20140308;
import android.content.Context;
public class MainButton extends LinearLayout {
private Drawable drawable;
private Drawable drawablebg;
public ImageButton mImage;
TextView mText;
private int size;
String text = "";
public MainButton(Context context) {
super(context);
}
public MainButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray localTypedArray = context.obtainStyledAttributes(attrs,
R.styleable.MyButton);
if (localTypedArray.hasValue(R.styleable.MyButton_MyButtonIcon)) {
this.drawable = localTypedArray
.getDrawable(R.styleable.MyButton_MyButtonIcon);
}
if (localTypedArray.hasValue(R.styleable.MyButton_MyBackground)) {
this.drawablebg = localTypedArray
.getDrawable(R.styleable.MyButton_MyBackground);
}
if (localTypedArray.hasValue(R.styleable.MyButton_MyButtonSize)) {
this.size = ((int) localTypedArray.getDimension(
R.styleable.MyButton_MyButtonSize, 0.0F));
}
this.mImage = new ImageButton(context, attrs);
this.mImage.setImageDrawable(this.drawable);
this.mImage.setAdjustViewBounds(true);
this.mImage.setBackgroundDrawable(this.drawablebg);
this.mImage.setLayoutParams(new LinearLayout.LayoutParams(
getResources().getInteger(R.integer.imagebutton_w),
getResources().getInteger(R.integer.imagebutton_h)));
this.mImage.setClickable(true);
this.mImage.setFocusable(true);
this.mText = new TextView(context, attrs);
this.mText.setPadding(0,
getResources().getInteger(R.integer.padding_top), 0, 0);
this.mText.setTextSize(this.size);
this.mText.setTextColor(Color.rgb(81, 81, 81));
this.mText.setGravity(1);
this.mText.setClickable(false);
this.mImage.setFocusable(false);
setOrientation(1);
addView(this.mImage);
addView(this.mText);
localTypedArray.recycle();
}
}
我尝试使用ImageButton和TextView为我的应用程序创建组合控件,我希望ImageButton可以响应click事件而TextView没有.Howerer,当我尝试在我的应用程序中使用它时,我发现结果相反,只有当我触摸TextView时,组合控件才能响应。下面是我的活动代码:
package com.example.test20140308;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainButton buutonButton = (MainButton) findViewById(R.id.btnSavedetail1);
buutonButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "cc", Toast.LENGTH_LONG)
.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
我的英语不够好,也许你会感到困惑,请指出来,谢谢!