Jonathan Beaudoin
Jonathan Beaudoin

Reputation: 2188

Align TextView Text Vertically Programmatically (No XML)

Working on a small project for a friend of mine and I'm having trouble aligning the text vertically when using a TextView

Here is my Activity class (Pure java no XML):

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;

public class WeightHistory extends AppCompatActivity {

    WeightLog[] history = {new WeightLog(30030, 100, 50), new WeightLog(30030, 50, 55), new WeightLog(30030, 55, 40), new WeightLog(30030, 40, 40)};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ListView list = new ListView(this);
        list.setAdapter(new MyAdapter(this, history));
        setContentView(list);
    }

    private class MyAdapter extends ArrayAdapter<WeightLog> {

        public MyAdapter(Context context, WeightLog[] logs) {
            super(context, -1, -1, logs);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LinearLayout listLayout = new LinearLayout(WeightHistory.this);
            listLayout.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT));

            WeightLog weightLog = super.getItem(position);
            TextView listText = new TextView(WeightHistory.this);
            listText.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT, 1f));

            listText.setGravity(Gravity.START | Gravity.CENTER);

            listLayout.addView(listText);
           /* if (weightLog.lostWeight() || weightLog.gainedWeight()) {
                listText.setTextColor(Color.WHITE);
                listText.setBackgroundColor(weightLog.lostWeight() ? Color.GREEN : Color.RED);
            }*/
            listText.setText(weightLog.toString());

            return listLayout;
        }
    }

}

Here is the WeightLog class(the class that gets shown in the list) if you are curious

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Jonathan on 12/8/2015.
 */
public final class WeightLog {

    private final long time;
    private final double lastWeight, currentWeight;


    public WeightLog(long time, double lastWeight, double currentWeight) {
        this.time = time;
        this.lastWeight = lastWeight;
        this.currentWeight = currentWeight;
    }

    public boolean lostWeight() {
        return currentWeight < lastWeight;
    }

    public boolean gainedWeight() {
        return currentWeight > lastWeight;
    }

    @Override
    public String toString() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(time));
        int day = cal.get(Calendar.DAY_OF_MONTH);
        SimpleDateFormat month_date = new SimpleDateFormat("MMM");
        String month_name = month_date.format(cal.getTime());
        return "Week of " + month_name + " " + formatDay(day) + ":\t\t\t\t\t\t" + lastWeight + "\t\t\t\t\t\t" + currentWeight + "\t\t\t\t\t\t" + (lastWeight == currentWeight ? "=" : lastWeight < currentWeight ? "+" : "-");
    }

    public String formatDay(int day) {
        int j = day % 10,
                k = day % 100;
        if (j == 1 && k != 11) {
            return day + "st";
        }
        if (j == 2 && k != 12) {
            return day + "nd";
        }
        if (j == 3 && k != 13) {
            return day + "rd";
        }
        return day + "th";
    }
}

Here is the issue I am having:

Image of issue

As you can see the numbers are not aligned vertically.

How can I achieve this without using XML?

Upvotes: 2

Views: 72

Answers (1)

David Dalcino
David Dalcino

Reputation: 51

In WeightLog.toString(), for this line:

return "Week of " + month_name + " " + formatDay(day) + 
    ":\t\t\t\t\t\t" + lastWeight + "\t\t\t\t\t\t" + currentWeight + "\t\t\t\t\t\t" + 
    (lastWeight == currentWeight ? "=" : lastWeight < currentWeight ? "+" : "-");

Try using String.format(). Documentation is here: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)

Using String.format(), this line would become the following:

return String.format("Week of %s %4s: %10.1f %10.1f %10s", 
            month_name, formatDay(day), lastWeight, currentWeight, 
            (lastWeight == currentWeight ? "=" : 
                lastWeight < currentWeight ? "+" : "-")
            );

I haven't actually tried this in an Android project, but in a Java console program, this code makes all the numbers line up perfectly. If this doesn't work the way you want it to in Android, you'll either need to switch to an monospaced font, or use XML. I could be wrong, but I think XML is the solution that Google would want you to use.

You may need to play around with the format string to get the display to appear the way you want it to; documentation is at: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Upvotes: 1

Related Questions