1:自定义的view中需要获取Context,在构造方法中定义即可,然后初始化界 面可控件!(这里调用一个button按钮)
public class Views extends RelativeLayout{
private Button btu;
private Context context;
public Views(final Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
LayoutInflater.from(context).inflate(R.layout.aaa, this);
btu = (Button) findViewById(R.id.button1);
btu.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
context.startActivity(new Intent(getContext(), MainActivity.class));
}
});
}
}
2:一般情况下设置一个Context为全局变量,方便调用,不过调用较少的话,可以不用设置全局变量,直接调用构造方法中的即可!(上面已经实现)
3:在自己的activity中初始化自定义的类,然后就获得button的点击效果
public class OtherActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
Views view = new Views(this, null);
view = (Views) findViewById(R.id.button);
}
}
补充4:Activityde的布局为:(中间是引用自定义的Views)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".OtherActivity" >
<cn.com.example.donghua.Views
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
</cn.com.example.donghua.Views>
</RelativeLayout>