2013-09-26 58 views
1

我正在使用下面的代碼來設置imageview的寬度。但它不起作用。如何在android中使用onTouch設置imageview的高度和寬度

XML:

`

<ImageView 
     android:id="@+id/card2" 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_marginBottom="3dp" 
     android:layout_marginTop="120dp" 
     android:layout_toRightOf="@+id/card1" 
     android:contentDescription="@string/slot" 
     android:src="@drawable/spade_3" />` 

和java:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_play__computer); 
    card1 = (ImageView)findViewById(R.id.card1); 
    card2 = (ImageView)findViewById(R.id.card2);   
    card1.setOnTouchListener(new ChoiceTouchListener()); 
    card2.setOnTouchListener(new ChoiceTouchListener()); 
} 
private final class ChoiceTouchListener implements OnTouchListener{ 

    public boolean onTouch(View v, MotionEvent event) { 

     if (event.getAction() == MotionEvent.ACTION_DOWN){ 
      v.getLayoutParams().width = 100; 
      return true; 
     } else{ 
      return false; 
     } 

    } 
} 

當我觸碰圖像視圖,它什麼都不做。

回答

1

試試這個

RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams) v.getLayoutParams(); 
param.width=200; 
v.setLayoutParams(param); 

希望它能爲你工作。

+0

它適合我。多謝兄弟。 – nick

+0

你總是受歡迎... @nick – arjunkn

+0

@arjunkn ...我如何設置默認位置,當我再次點擊該圖像視圖?我使用if()但沒有用。 – nick

0

試試這個:

private final class ChoiceTouchListener implements OnTouchListener{ 

    public boolean onTouch(View v, MotionEvent event) { 

     if (event.getAction() == MotionEvent.ACTION_DOWN){ 
      ImageView imgView = (ImageView) v; 

      int width = 100; 
      int height = 100; 

      LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height); 
      imgView.setLayoutParams(layoutParams); 

      return true; 
     } else{ 
      return false; 
     } 
    } 
} 
+0

正在使用相對佈局。這對我有用嗎? – nick

0

使用的LayoutParams設置高度和寬度:

RelativeLayout layout = new RelativeLayout(this); 
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, 
      LayoutParams.WRAP_CONTENT); 

您可以從代碼中訪問任何的LayoutParams使用View.getLayoutParams

+0

感謝您的回答。我如何在RelativeLayout中使用它? – nick

+0

看到我更新的答案 –

+1

它起作用。謝謝 – nick

相關問題