Android - Call an xml layout file in a class that extends View
-
25-05-2021 - |
Вопрос
I want to call my XML layout file in a class that extends view. I can't perform oncreate function in that because it does not extends Activity. My events are in the one class file and I am calling that class in another class file; but I want to perform those events on XML layout file.
Here is my code:
Demo.java
public class Demo extends Activity
{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new another(this));
}
another.java
public class another extends View
{
public anotherView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public anotherView(Context context) {
super(context);
init();
}
public anotherView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setWillNotDraw(false);
...
..
..
}
And XML file
abc.xml
..
..
How to do it?
Решение
If you want to add an item to your View you could always inflate it.
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.ABC, null);
addView(view);
Другие советы
If what you want is to get an item from your XML
you should call
[yourviewType]View v1 = (Cast-to-type-of-view)context.findViewById(R.id.idOfView);
Example :
TextView tv1 = (TextView)findViewById(R.id.aboutText);
is this what you need ?
Не связан с StackOverflow