Creating a layout within a View-extended class
I am still pretty new to Android development, and I have not been able to find any examples of how to do this.
In my Activity, I use "setContextView(new myViewClass)" to designate a View-extended class as the one to load. Everything works fine in terms of loading the view, where I create various elements (LinearLayouts, buttons, etc.) based on a number of conditions. Unfortunately, I cannot get any of these elements to actually appear on the screen.
I guess my question goes to a greater understanding of Views. All of the examples I've seen concern setting an xml file as the base view and then altering it within the code. Is there some alternative to this?
Thanks.
Here is an example code I've been trying to make work. There are other things going on, but this is the relevant info. For program context, this class is substantiated with the setContextView(new createView(this))
:
public createView(Context c){
super(c);
// Create a simple layout
LinearLayout layout = new LinearLayout(top.getContext());
layout.setOrientation(LinearLayout.VERTICAL);
// Create test text
开发者_运维问答 TextView mTestText = new TextView(c);
mTestText.setText("This is a test");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(10, 10, 10, 10);
layout.addView(mTestText, lp);
}
I think the problem is that you are not adding the layout to your CreateView. However, the View class does not have an add method (see http://developer.android.com/reference/android/view/View.html).
Since LinearLayout is the base view for your extended view, you could extend LinearLayout instead and add the TextView to your extended class. If you do this, your CreateView class would probably look something like this:
/**
* Since the LinearLayout is the base layout, we'll extend it.
*/
public class CreateView extends LinearLayout {
public CreateView(Context context) {
super(context);
setOrientation(LinearLayout.VERTICAL);
TextView mTestText = new TextView(context);
mTestText.setText("This is a test");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(10, 10, 10, 10);
addView(mTestText, lp);
}
}
精彩评论