Android - 视图在ListView滚动上丢失填充

时间:2012-12-10 05:28:30

标签: android android-ui

我有TextView

<TextView
    android:background="@drawable/myshape"
    android:padding="5dp"
    ... />

将以下形状设置为背景:

<shape>
    <corners android:radius="4dp" />
    <solid android:color="#FFFAD6" />
</shape>

TextView显示在ListView内。问题是滚动时填充丢失。列表视图首次呈现时看起来很好:

enter image description here

当列表来回滚动时,填充将丢失:

enter image description here

我错过了什么?

修改以下是代码:

public class MyArrayAdapter extends ArrayAdapter<MyBean> {

    private Context context;
    private List<MyBean> myBeans;

    public MyArrayAdapter(Context context, int resource, int textViewResourceId, List<MyBean> myBeans) {
        super(context, resource, textViewResourceId, myBeans);
        this.context = context;
        this.myBeans = myBeans;
    }

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

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.my_activity, parent, false);
        }

        MyBean bean = myBeans.get(position);
        setData(row, bean);
        return row;
    }

    private void setData(View layout, MyBean bean) {
        TextView dateHeader = (TextView) layout.findViewById(R.id.dateHeader);
        dateHeader.setText(bean.getDate());

        TextView textView1 = (TextView) layout.findViewById(R.id.box);
        textView1.setText("textView 1");

        TextView box = (TextView) layout.findViewById(R.id.box);
        box.setText(Html.fromHtml("<b>Foo</b><br><small>Bar</small>"));
        // etc..
    }
}


public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);

        ListView listView = new ListView(this);
        setContentView(listView);
        ArrayAdapter<MyBean> arrayAdapter = new MyBeanArrayAdapter(
                this, R.layout.my_activity, R.id.dateHeader, getBeans());

        listView.setAdapter(arrayAdapter);
    }

}

更新在玩完之后,我发现这种情况正在发生,因为文本被拆分为2行(使用<br>\n):

box.setText(Html.fromHtml("<b>Foo</b><br><small>Bar</small>"));
box.setText("Foo \n Bar");

当我删除<br>\n时,TextView框会保留其大小。

然而,我还没有解决方案。接受建议。

1 个答案:

答案 0 :(得分:1)

我也遇到过类似的行为。当您在列表适配器中回收视图时,看起来布局参数会丢失。我最终在我的适配器的 getView()方法中设置了布局参数。您可以在getView()中尝试setPadding(int left,int top,int right,int bottom),看看它是否解决了问题。