开发者

Fill XML view at runtime with instance of custom View

I've got a custom View that I define at runtime. I don't want it to fill the screen, I want it to be inside a larger layout that's defined in XML.

This is what I'd lik开发者_StackOverflowe to do in pseudo code:

View newView = new MyCustomView();
View.replace(newView , R.id.old_view);

Any ideas?

Thanks


I suggested using a ViewStub in the comments above, but I think that might be overkill. You could just try this:

package com.example.viewstub;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ViewStubTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView old_textview = (TextView )this.findViewById(R.id.textView1);
        old_textview.setVisibility(View.INVISIBLE);

        TextView tv = new TextView(this.getApplicationContext());
        tv.setText("new Text!!!");

        LinearLayout ll = (LinearLayout)this.findViewById(R.id.linearLayout_1);
        ll.addView(tv);
    }
}

It's just getting reference to the top level layout, adding the new component and removing the old one. I think it should do the trick.

Casp

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜