我创建了一个复合视图,它包含三个视图,两个ImageButtons
和一个EditText。我试图在每次点击按钮时创建新的“MyView
”视图。首先,我决定在xml中设置onClick,希望每次创建一个新的MyView时,它都会设置监听器,但它似乎不起作用。所以我的问题是,如何设置onClick监听器,复合视图中的按钮,以及方法是否在其他类中?我正在谈论的方法是ViewControl
vlass
MyView.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:layout_width="0sp"
android:layout_height="wrap_content"
android:id="@+id/text"
android:layout_weight="80" />
<ImageButton
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight="10"
android:id="@+id/add"
android:onClick="addViewBelow"
android:clickable="true"
android:background="@drawable/add" />
<ImageButton
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight="10"
android:id="@+id/rmv"
android:background="@drawable/rmv" />
</LinearLayout>
MyView.java
public class MyView extends LinearLayout {
private EditText txt;
private ImageView add, rmv;
public MyView(Context context)
{
super(context);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.myview, this);
txt = (EditText) findViewById(R.id.text);
add = (ImageView) findViewById(R.id.add);
rmv = (ImageView) findViewById(R.id.rmv);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.myview, this);
txt = (EditText) findViewById(R.id.text);
add = (ImageView) findViewById(R.id.add);
rmv = (ImageView) findViewById(R.id.rmv);
}
ViewControl.java
public class ViewControl implements OnClickListener {
LinkedList<MyView> pathView;
Button mainButton;
RelativeLayout rl;
Activity act;
int lastId;
public ViewControl(Activity activity) {
act = activity;
//stuff
}
@Override
public void onClick(View v) {
//stuff
}
public void addViewBelow() {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, lastId);
MyView mv = new MyView(act);
mv.setId(UniqueID.generateViewId());
mv.setLayoutParams(params);
lastId = mv.getId();
pathView.add(mv);
rl.addView(pathView.getLast());
}
}
答案 0 :(得分:3)
要使android:onClick
起作用,该方法必须位于View的上下文中,该上下文通常是一个Activity。
对于您的情况,我建议如下:
将此方法添加到MyView:
public void setClickListener(OnClickListener listener){
add.setOnClickListener(listener);
}
在addViewBelow
中执行此操作:
mv.setClickListener(new OnClickListener(){
@Override
public void onClick(View v){
addViewBelow();
}
});