RatingBar組件的應用(星形)

 

如圖所示,通過點擊星形圖標進行評分。看似簡單,操作起來卻也得細心呢!

下面就看看怎麼完成它呢:

 

一 佈局:

這個相對簡單,只有一個activity_main.xml:

<LinearLayout 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:background="@drawable/bg"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/padding_medium"
        android:text="請您評分:"
        tools:context=".MainActivity" />

    <RatingBar
        android:id="@+id/ratingBar1"
        style="@style/AppTheme"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:rating="0.5"
        android:stepSize="0.5" />

    <TextView
        android:id="@+id/corse"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:padding="@dimen/padding_medium"
        android:text="評分結果爲:"
        tools:context=".MainActivity" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/descrption"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="推薦指數:" />

        <RatingBar
            android:id="@+id/ratingBar2"
            style="?android:attr/ratingBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:isIndicator="false" />
    </LinearLayout>

</LinearLayout>

二 中心文件:

public class MainActivity extends Activity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //定義組件對象
        final RatingBar rb1=(RatingBar) findViewById(R.id.ratingBar1);
        final RatingBar rb2=(RatingBar) findViewById(R.id.ratingBar2);
       
		 rb1.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
	        	
				@Override
				public void onRatingChanged(RatingBar ratingBar, float rating,
						boolean fromUser) {
					 // corse.setText(rating);
					  rb1.setRating(rating);
					  rb2.setRating(4);
					  Toast.makeText(MainActivity.this, "評分結果是:"+String.valueOf(rating)+"分", Toast.LENGTH_LONG).show();
					
					
				}
			});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章