开发者

quirky (possibly stupid) attempt to inflate a view into an instance of extended View object

开发者 https://www.devze.com 2023-04-12 04:53 出处:网络
I have created a TableRow layout model which I\'m using as a template for a custom View that extends TableRow.开发者_运维百科

I have created a TableRow layout model which I'm using as a template for a custom View that extends TableRow.开发者_运维百科

My desire is to inflate the row inside the extended class, AND have that inflated instance BE the extended row.

In pseudo code:

public class MyTableRow extends TableRow{
    if(conditionA)
       this = (TableRow)inflate(R.layout.myModelRowA);
    if(conditionB)
       this = (TableRow)inflate(R.layout.myModelRowB);
    etc...
}

And then when I'm adding these rows to the table I'd proceed as usual...

myTable.addView(new MyTableRow(this));

So, the issue is that obviously I can't assign things to this even if logically it makes perfect sense, since in the example above this is a TableRow.

Is there another way to do this? I know it looks stupid, but my current alternative is to house the inflated TableRow as a member of MyTableRow, which works, but is really ugly (and doesn't feel very OO).

Am I missing something obvious? Or should I just settle for what I have?


Define your Row A and Row B layouts with tag <merge> (see here) instead of <TableRow>:

<merge xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Other component declarations here  -->
</merge>

then inflate one of these layouts in your extended row constructor:

public MyTableRow(Context context, AttributeSet attrs) {
    super(context, attrs);
    if (condA) {
        inflate(context, R.layout.RowA, this);
    } else {
        inflate(context, R.layout.RowB, this);
    } 
}

Then in your Table layout use your extended Row instead of TableRow:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">

    <your.package.name.MyTableRow>

    </your.package.name.MyTableRow>

</TableLayout>


Not sure what you are exactly looking for but you can get the view and do a get context. Something like View view = (TableRow)inflate(R.layout.myModelRowA); Context ctx = view.getContext();

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号