2017-05-02 65 views
0

如何在按下按鈕時更改矩形按鈕的描邊寬度?如何以編程方式更改形狀矩形的描邊寬度

我在我的自定義按鈕的可繪製文件夾中創建了一個xml文件。

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
    <corners 
     android:radius="9dp"/> 
    <gradient 
     android:angle="45" 
     android:centerX="9%" 
     android:centerColor="#84edb2" 
     android:startColor="#07e7cb" 
     android:endColor="#b0ede3" 
     android:type="linear" 
     /> 
    <size 
     android:width="40dp" 
     android:height="30dp" 
     /> 
    <stroke 
     android:width="2dp" // I want to change this programmatically. 
     android:color="#2f7E87" 
     /> 
</shape> 

以下是我的java代碼。 我想在按下按鈕時更改按鈕的筆觸寬度。

public static void buttonEffect(View button){ 
    button.setOnTouchListener(new View.OnTouchListener() { 
     ShapeDrawable circle = new ShapeDrawable(new OvalShape()); 


     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      switch (event.getAction()) { 
       case MotionEvent.ACTION_DOWN: { 
        Button view = (Button) v; 
        int col = Color.parseColor("#40E0D0"); 
        view.getBackground().setColorFilter(col, PorterDuff.Mode.SCREEN); 
        v.invalidate(); 

        break; 
       } 
       case MotionEvent.ACTION_UP: 
        // Your action here on button click 
       case MotionEvent.ACTION_CANCEL: { 
        Button view = (Button) v; 
        view.getBackground().clearColorFilter(); 
        view.invalidate(); 
        break; 
       } 
      } 
      return true; 
     } 

    }); 
} 

回答

1

我認爲的解決方案是: +創建兩個不同大小的描邊繪製的形狀。 +當觸摸按鈕時,只需將背景更改爲其他可繪製的。

+0

我是新到Android,你能告訴我怎麼做,我不知道 –

2

嘗試下面的解決方案,它會幫助你有希望解決你的問題。

Here is a screenshot, Have a look

GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{ContextCompat.getColor(this,R.color.red_500), 
     ContextCompat.getColor(this,R.color.red_500), ContextCompat.getColor(this,R.color.red_500)}); 
gd.setShape(GradientDrawable.RECTANGLE); 
gd.setStroke((int)0.5, ContextCompat.getColor(this, R.color.black)); 
gd.setCornerRadius(8f); 
gd.setBounds(2, 2, 2, 2); 
btnCreateUser.setBackground(gd); 

當您點擊按鈕,根據您的要求在此行行程的設置寬度,這樣你就不必使用XML了

i.e: gd.setStroke((int)1, ContextCompat.getColor(this, R.color.black)); 
i.e: gd.setStroke((int)3, ContextCompat.getColor(this, R.color.black)); 
+0

**感謝的人偉大的工作** –

+0

很高興它幫助你... – Bhavnik

1

它基於@DươngNguyễnVăn答案。

您有一個按鈕,默認筆畫寬度爲2dp。現在當你按下它時,它的筆畫寬度會變成4dp。
因此,您創建了兩個可繪製文件:bg_button_2.xml(行程寬度= 2dp)bg_button_4.xml(行程寬度= 4dp)。

現在,您可以通過編程方式更改其背景。

button.setOnClickListener(new View.OnClickListener() { 
     @Override public void onClick(View view) { 
     button.setBackgroundResource(R.drawable.bg_button_4); 
     } 
}); 
相關問題