以编程方式在AlertDialog上设置分隔符

时间:2015-09-24 14:14:59

标签: android alertdialog

如何以编程方式在AlertDialog的第一个元素上设置分隔符?

我已经尝试了这个,其他SO答案:

mStoreMenu.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface dialog) {
        Dialog d = ((Dialog) dialog);

        int titleId = d.getContext().getResources().getIdentifier("android:id/alertTitle", null, null);
        TextView titleView = (TextView) d.findViewById(titleId);
        titleView.setTextColor(getResources().getColor(R.color.my_color));

    }
});

我遇到了崩溃

9-24 10:08:33.817    5697-5697/com.shopkeep.pocketandroid E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.shopkeep.pocketandroid, PID: 5697
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundColor(int)' on a null object reference
            at com.shopkeep.pocketandroid.MainActivity.showMenu(MainActivity.java:162)
            at com.shopkeep.pocketandroid.MainActivity.toggleMenu(MainActivity.java:79)
            at com.shopkeep.pocketandroid.MainActivity$1.onClick(MainActivity.java:62)
            at android.view.View.performClick(View.java:4780)

我也尝试在显示之后设置颜色,同样的问题。

2 个答案:

答案 0 :(得分:0)

试试,

Resources res = getResources();
int titleDividerId = res.getIdentifier("titleDivider", "id", "android");
View titleDivider = dialog.findViewById(titleDividerId);
if (titleDivider != null) {
    titleDivider.setBackgroundColor(res.getColor(R.color.my_color));
}

答案 1 :(得分:0)

View line = new View(context);
 line.setBackgroundColor(0xFF00FF00);

parent.addView(line,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,2));