我有一个图像视图,其中我使用OnClickListener,这样我就有一个自定义按钮。
我在imageView旁边也有文本,但是我希望它们也能够在文本附近单击。
我想知道是否可以创建一个可绘制文件并且只有一个按钮。
这是我到目前为止所拥有的:https://i.stack.imgur.com/3BeR5.png
您可以使用常规按钮执行此操作。使用drawableLeft
和drawableRight
属性设置图像。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/backButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:drawableLeft="@drawable/ic_chevron_left_white_24dp"
android:text="Back" />
<Button
android:id="@+id/nextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:drawableRight="@drawable/ic_chevron_right_white_24dp"
android:text="Next" />
</RelativeLayout>
您还可以设置android:background="@null"
以删除按钮轮廓并仅显示文本和图标。 它将看起来更接近您的屏幕截图,用户可以单击图标或文本,按钮将获得单击。
创建自定义视图:
package com.android4dev.navigationview;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;
/**
* Created by 77930 on 2016/1/24.
*/
public class MyView extends ImageView {
public interface OnAreaClickListener{
public void onLeftClick(MyView view);
public void onRightClick(MyView view);
}
public OnAreaClickListener listener;
public OnAreaClickListener getListener() {
return listener;
}
public void setListener(OnAreaClickListener listener) {
this.listener = listener;
}
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if(event.getX() < getWidth()/3){
if(listener!=null) listener.onLeftClick(MyView.this);
}else if(event.getX() > getWidth()/3){
if(listener!=null) listener.onRightClick(MyView.this);
}
}
return super.onTouchEvent(event);
}
}
添加布局:
<com.android4dev.navigationview.MyView
android:id="@+id/btn_all"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:src="@mipmap/ic_launcher"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
绑定点击:
MyView myView = (MyView)findViewById(R.id.btn_all);
myView.setListener(new MyView.OnAreaClickListener() {
@Override
public void onLeftClick(MyView view) {
}
@Override
public void onRightClick(MyView view) {
}
});