2015年7月20日 星期一

「Android」製作一個圓形的View,並且可以自定顏色

View要變成圓形,可以透過下列程式。


activity_main.xml


 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"  
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">  
   <TextView  
     android:layout_width="300dp"  
     android:layout_height="300dp"  
     android:textAppearance="?android:attr/textAppearanceMedium"  
     android:id="@+id/color_text"  
     android:layout_centerVertical="true"  
     android:layout_alignParentRight="true"  
     android:layout_alignParentEnd="true"  
     />  
 </RelativeLayout>  

MainAcitvity.java

import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView color_txt=(TextView)findViewById(R.id.color_text);

        ShapeDrawable sw=dymanticShap();

        int pixel= Color.GREEN;

        sw.getPaint().setColor(pixel);

        color_txt.setBackground(sw);

    }
    private ShapeDrawable dymanticShap()
    {
        ShapeDrawable footerBackground = new ShapeDrawable();

        OvalShape os=new OvalShape();

        footerBackground.setShape(new OvalShape());


        return footerBackground;
    }
}


執行結果

沒有留言:

張貼留言