前言
网上看了很多文章,都用到了反射,我尝试过了,在高版本安卓系统中,会出现无效的情况,因为在高版本系统上,官方对反射作出了限制。本篇文章根据DatePicker的布局结构去实现界面改造,DatePicker的界面布局结构如下图: 
代码
因为代码很简单,所以不做过多的解释。
布局
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
tools:context=".MainActivity">
<DatePicker
android:id="@+id/datePicker"
android:layout_width="match_parent"
android:datePickerMode="spinner"
android:calendarViewShown="false"
android:background="#f1f2f3"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private DatePicker datePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datePicker=findViewById(R.id.datePicker);
LinearLayout linearLayout1 = (LinearLayout) datePicker.getChildAt(0);
LinearLayout linearLayout2 = (LinearLayout) linearLayout1.getChildAt(0);
linearLayout2.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,400));
linearLayout2.getChildAt(2).setVisibility(View.GONE);
NumberPicker numberPicker1 = (NumberPicker) linearLayout2.getChildAt(0);
NumberPicker numberPicker2 = (NumberPicker) linearLayout2.getChildAt(1);
numberPicker1.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
numberPicker2.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
numberPicker1.setSelectionDividerHeight(3);
numberPicker2.setSelectionDividerHeight(3);
numberPicker1.setTextColor(Color.parseColor("#ff0000"));
}
}
截图

总结
本次的效果图中并未涉及到修改分割线的颜色,因为看了NumberPicker的方法结构图,如下所示:  并没有public方法去对分割线的颜色进行修改。本篇文章不推荐使用反射,如果想要修改分割线的颜色,请参看我的另一篇文章“修改DatePicker的分割线颜色”。 注意:我看过有些书籍,上面的第二个LinearLayout其实有些机型可能存在5个Child,也就是除了年、月、日滚动控件之外,还有2条分割线,如下图: 所以需要对孩子的个数作出判断(ViewGroup有个getChildCount方法可以判断子视图的个数),然后做兼容性处理。
|