How to synchronize the drawable state of two views
In Android I have an EditText and a Button next to the EditText, and whenever I press on one I would like the other to appear in the same state as well.
I tried putting android:clickable = "true" on the enclosing layout and android:duplicateParentState="true" on my EditText and Button but this only works if I touch the layout itself. If I touch my EditText or Button nothing happens. I tried setting android:clickable = "false" on t开发者_C百科he EditText & Button but the touch events still don't filter down to the parent.
How can I make my views transparent to touch events so they pass down to the parent? What I want is for the EditText and Button to work together so if I touch either one they both appear to be pressed.
Here is the XML I am currently using:
<RelativeLayout
android:id = "@+id/EnclosingLayout"
android:layout_width = "fill_parent"
android:layout_height = "120dp"
android:clickable = "true">
<EditText
android:id = "@+id/MyEditText"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:layout_weight = "1"
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
android:duplicateParentState="true"/>
<Button
android:id = "@+id/MyButton"
android:layout_alignTop="@id/MyEditText"
android:layout_alignBottom="@id/MyEditText"
android:layout_alignParentRight="true"
android:duplicateParentState="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="31.33dp"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:clickable="false"/>
</RelativeLayout>
I think you want android:focusable="true"
in your RelativeLayout instead of clickable. Im not sure what you mean by "How can I make my views transparent to touch events so they pass down to the parent?" When you click on the EditText you want the Buttons onClick() to get called?
Consider trapping all input to the edit text and button and redirecting the event to a common view controller, in this case, a common method. Then update both the edit text and button in the common method (a view controller). For the edit text you will need to trap both on touch and on click by creating a handler for both events as in:
// EDIT TEXT ON TOUCH HANDLER
editTextPassword.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
SynchViews(); // view controller
break;
}
return true;
}
});
// EDIT TEXT ON Click HANDLER (No touch screen)
editTextPassword.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SynchViews(); // view controller
}
});
精彩评论