shape檔案用法二:在Android中,用XML檔案實現圓角的效果
阿新 • • 發佈:2019-02-19
需求:好多時候,需要給元件加入圓角的效果,如下圖所示:
現在,要做的就是,實現 圖中所示的圓角效果。
第一步:在 res/drawable檔案下新增 ,檔案: btn_background_shape.xml 檔案。 /TestShape2/res/drawable/btn_background_shape.xml
程式碼如下:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <!-- 這塊的 corner重要作用是 控制:那個圓角的半徑,值越大,半徑越大!圓角的弧度就越大 --> <corners android:radius="15dp"/> <solid android:color="#ffffff"/> <gradient android:startColor="#4EC9D8" android:endColor="#030" android:angle="90" /> </shape>
第二步:為要實現這個效果的元件,引入這個檔案:
程式碼如下:
<?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="match_parent" android:gravity="center" android:orientation="vertical" > <!-- background 即引入:所需效果的 shape --> <Button android:layout_width="150dp" android:layout_height="150dp" android:text="Hello Shape" android:layout_gravity="center" android:background="@drawable/btn_background_shape" /> </LinearLayout>
第三步:在程式碼中引入,即可實現:
package com.zhanggeng.testshape2; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
如此,便可大功告成!