android - How to set background color to a dynamically created view?


Keywords:android 


Question: 

I am creating events. I have created dynamic view for event.

Now I want to set colors to my events. I have created xml file and event structure in that. I have set drawable for this view.

This drawable has shape of rectangle. So event's shape I get as a rectangle. Now when I am setting color into database and retrieving it from database to show on event.

It dose not show in a event's shape. Like below is a screenshot. enter image description here

How to add this color with shape?

Event view xml layout:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/Parent">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/shape"
        android:id="@+id/container"
        android:layout_marginLeft="60dp"
        android:layout_marginRight="12dp">

        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
            android:id="@+id/textViewTitle"
            android:layout_marginLeft="10dp"
            android:textColor="@android:color/white"
            android:layout_marginTop="01dp"
            android:layout_alignParentStart="true" />

    </RelativeLayout>
</RelativeLayout>

Shape drawable :

<?xml version="1.0" encoding="utf-8"?>

    <shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">


    <stroke android:width="2dip"/>

    <stroke android:color="@color/black" android:width="1dip"/>
    <corners android:radius="4dp"> </corners>

</shape>

Mon fragment :

public class Mon extends Fragment {

    private FrameLayout fab;
    private EventTableHelper mDb;
    private Intent i;
    private ViewGroup dayplanView;
    private int minutesFrom,minutesTo;
    private List<EventData> events;
    private List<View> list;
    private EventData e;
    private LayoutInflater inflater;
    public  boolean editMode;
    private RelativeLayout container;
    RelativeLayout parent;
     View eventView;
    private boolean mCheckFragment;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mon, container, false);
        list = new ArrayList<View>();


        dayplanView = (ViewGroup) view.findViewById(R.id.hoursRelativeLayout);

        showEvents();


        mCheckFragment = true;


        return view;
    }

    private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title,String location,final int id,int color) {

       eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();

        container = (RelativeLayout) eventView.findViewById(R.id.container);
        TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
        list.add(eventView);

        eventView.setBackgroundColor(color);

        if (tvTitle.getParent() != null)
           ((ViewGroup) tvTitle.getParent()).removeView(tvTitle);

        if(location.equals(""))
        {
            tvTitle.setText("Event : " + title);
        }
        else
        {
            tvTitle.setText("Event : " + title + " (At : " + location +")");
        }
        int distance = (toMinutes - fromMinutes);
        layoutParams.topMargin = dpToPixels(fromMinutes + 9);
        layoutParams.height = dpToPixels(distance);

        eventView.setLayoutParams(layoutParams);
        dayplanView.addView(eventView);
        container.addView(tvTitle);



        eventView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                i = new Intent(getActivity(), AddEventActivity.class);
                editMode = true;
                i.putExtra("EditMode", editMode);
                i.putExtra("id", id);
                startActivityForResult(i, 1);

            }
        });
    }

    public void showEvents()
    {
        mDb = new EventTableHelper(getActivity());
        events = mDb.getAllEvents("Mon");

        for (EventData eventData : events) {

            int id = eventData.getId();
            String datefrom = eventData.getFromDate();

            if (datefrom != null) {
                String[] times = datefrom.substring(11, 16).split(":");
                minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
            }
            String title = eventData.getTitle();
            String location = eventData.getLocation();
            String dateTo = eventData.getToDate();
            int color = eventData.getColor();


            if (dateTo != null) {
                //times = dateTo.substring(11,16).split(":");
                String[] times1 = dateTo.substring(11, 16).split(":");
                minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]);
            }
            createEvent(inflater, dayplanView, minutesFrom, minutesTo, title, location, id, color);
            id++;


        }
    }

    public void removeView()
    {
        for(int i=0; i<list.size(); i++)
        {
            View view = (View)list.get(i);
            dayplanView.removeView(view);
        }
    }

    private int dpToPixels(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }

    @Override
    public void onResume()
    {

        super.onResume();

        if(mCheckFragment)
        {
            removeView();
            showEvents();

        }

    }

}

Thank you..


2 Answers: 

change line

eventView.setBackgroundColor(color);

to

container.setBackgroundColor(color);

this might help you.

 
   Drawable drawable = eventView.getBackground();

    if (drawable instanceof GradientDrawable) {
        GradientDrawable gd = (GradientDrawable) drawable.getCurrent();
        gd.setColor(color);

    }
    if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
        eventView.setBackgroundDrawable(drawable);
    }
    else {

        eventView.setBackground(drawable);
    }