textview何时获取android中数组适配器的宽度?

时间:2014-11-06 16:08:32

标签: android textview android-arrayadapter

我有一个由自定义数组适配器填充的ListView。我使用holder设计模式为每行内的textview指定值。

我想在自定义ArrayAdapter中以编程方式设置TextView的边距。 此边距(左)是使用TextView的宽度计算的。

但不知何故textview上的getWidth()方法返回0

这是我的代码:

public class BudgetAdapter extends ArrayAdapter<Budget> {

    private Context context;
    private int layoutResourceId;
    private List<Budget> data = null;

    public BudgetAdapter(Context context, int layoutResourceId, List<Budget> data) {
        super(context, layoutResourceId, data);
        this.context = context;
        this.layoutResourceId = layoutResourceId;
        this.data = data;
    }



    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        BudgetHolder holder = null;

        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new BudgetHolder();
            holder.titleText = (TextView)row.findViewById(R.id.budget_list_item_title_label);
            holder.remainingText = (TextView)row.findViewById(R.id.budget_list_item_remaining_label);
            holder.remainingBar = (RemainingBar)row.findViewById(R.id.budget_list_item_remaining_bar);
            row.setTag(holder);
        }
        else
        {
            holder = (BudgetHolder)row.getTag();
        }

        Budget budget = data.get(position);
        holder.titleText.setText(budget.getShortDescription());
        holder.remainingText.setText(budget.getRemainingAsString());
        holder.remainingBar.setRemaining(budget.getRemaining());
        holder.remainingBar.setTotal(budget.getTotal());

        Log.i("Main", "The width of the TextView is: " + holder.remainingText.getWidth());
        return row;
    }


    static class BudgetHolder {
        TextView titleText;
        TextView remainingText;
        RemainingBar remainingBar;
    }
}

所以我的问题是TextView何时获得宽度?

1 个答案:

答案 0 :(得分:1)

  

TextView何时获得宽度?

如果动态生成View类(通过代码),它们将在屏幕上显示后获得宽度。

你的案子怎么样?

抱歉,我不知道。希望有人能帮助我们:)

但我可以用代码帮助你。尝试改变:

holder.remainingText.getWidth());

对于这样的事情:

holder.remainingText.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
holder.remainingText.getLayoutParams().width;
holder.remainingText.getLayoutParams().height;

您应该获得文字的宽度和高度。