layout from Java android sdk
Okay so I want to make a layout inside of a Java file and then I would like to call that Java file into my main acti开发者_如何学Govity. How would I go about this?
any help is greatly appreciated.
-thanks Christian
LayoutSample.java
public class LayoutSampler extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleLayoutDemo(this));
}
}
SampleLayoutDemo
class SampleLayoutDemo extends LinearLayout {
public SampleLayoutDemo(Context context) {
super(context);
TextView view = new TextView(context);
view.setText("Sample");
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
addView(view);
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
}
Create a class which extends Layout and call the layout in the activity setContentView() method.
in onCreate you say:
myView = new MyView(this);
setContentView(myView);
myView.requestFocus();
If you want to draw your own graphics then in java file you write:
public class MyView extends View{
public MyView(Context context){
super(context);
}
@Override
public void onDraw(Canvas canvas){
}
}
You can also set that MyView class extends LinearLayout etc and then use myView.addView() to create a nested layout.
I understand your question as "I want to use a LinearLayout or other existing ViewGroup in my Activity and then add views to that without using XML files". Is this correct? If you want to do custom views ChristianB already stated the basics. Custom layouts are quite tricky and I recommend subclassing existing viewgroups.
So if my assumption about your question is correct, you create a view in your activity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout (this);
TextView helloText = new TextView(this);
helloText.setText("Hello World");
layout.addView(helloText);
setContentView(layout);
}
You can exchange LinearLayout for any other ViewGroup, or skip the ViewGroup completely and add a single "fullscreen" view.
精彩评论