rafvasq
rafvasq

Reputation: 1510

set Padding on TextView programmatically

I am dynamically/programmatically adding TextViews to a preset LinearLayout but for some reason setting padding is not working. Both the text and font appear as expected, but padding doesn't seem to work. Comparing to other solutions online, seems like this should work. What am I doing wrong?

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    final CustomItem listItem = listItems.get(position);

    holder.Heading.setText(listItem.getHeading());

    ArrayList<String> directions = listItem.getDirections();
    for(int i = 0; i < directions.size(); i++) {
        TextView step = new TextView(context);
        step.setPadding(20, 20, 0, 20);
        step.setText(directions.get(i));
        step.setTypeface(ResourcesCompat.getFont(context, R.font.lato_light));
        holder.CustomLayout.addView(step);
    }
}

public class ViewHolder extends RecyclerView.ViewHolder{

    public LinearLayout LegLayout;
    public TextView Heading;

    public ViewHolder(View itemView) {
        super(itemView);

        Heading = itemView.findViewById(R.id.heading);
        LegLayout = itemView.findViewById(R.id.directionsLayout);

    }

}

Upvotes: 0

Views: 644

Answers (2)

navylover
navylover

Reputation: 13609

As official doc say,

Padding can be used to offset the content of the view by a specific amount of pixels

so need to convert dp to px like this:

float density = getResources().getDisplayMetrics().density;
int paddingPixel = (int) (20 * density);
step.setPadding(paddingPixel, paddingPixel, 0, paddingPixel);

Upvotes: 0

Pankaj Kumar
Pankaj Kumar

Reputation: 83028

It seems you are verifying on high resolution device. You need to use DP to PX conversion and then use that converted value to setPadding();

Method to convert dp to pixel is

public static int dpToPx(int dp) {
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

and your setPadding call would be

step.setPadding(dpToPx(20), dpToPx(20), 0, dpToPx(20));

Upvotes: 1

Related Questions