2015年4月10日 星期五

Android DatePicker Hide Year Month Day 日期選項 隱藏 年 月 日

隱藏原生的DatePicker的年或月
1./res/layout/main.xml


    

        

            
            

            
            

            
            

            
            

            
            

            
            
        
    


2.Main.java
package tw.android;

import java.lang.reflect.Field;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;

public class Main extends Activity {
 private DatePicker datePicker1, datePicker2;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  datePicker1 = (DatePicker) findViewById(R.id.datePicker1);
  datePicker2 = (DatePicker) findViewById(R.id.datePicker2);

  try {
   /* 隱藏年 */
   Field f1[] = datePicker1.getClass().getDeclaredFields(); // 建立datePicker1
   for (Field field : f1) {
    Log.i("f1's all field", field.getName() + ""); // log出f1的所有元素
    if (field.getName().equals("mYearSpinner")) { // 取得的元素等於mYearSpinner
     field.setAccessible(true);
     Object yearPicker = new Object();
     yearPicker = field.get(datePicker1);
     ((View) yearPicker).setVisibility(View.GONE); // 隱藏年
    }

   }
   /* 隱藏年、月 */
   Field f2[] = datePicker2.getClass().getDeclaredFields(); // 建立datePicker2
   for (Field field : f2) {
    Log.i("f2's all field", field.getName() + ""); // log出f2的所有元素
    if (field.getName().equals("mYearSpinner")) { // 取得的元素等於mYearSpinner
     field.setAccessible(true);
     Object yearPicker = new Object();
     yearPicker = field.get(datePicker2);
     ((View) yearPicker).setVisibility(View.GONE); // 隱藏年
    }

    if (field.getName().equals("mMonthSpinner")) { // 取得的元素等於mMonthSpinner
     field.setAccessible(true);
     Object monthPicker = new Object();
     monthPicker = field.get(datePicker2);
     ((View) monthPicker).setVisibility(View.GONE); // 隱藏月
    }

   }
  } catch (Exception e) {
   Log.d("ERROR", e.getMessage());
  }
 }
}


參考來源:
http://stackoverflow.com/questions/10401915/hide-year-field-in-android-datepicker

沒有留言 :

張貼留言