是否可以创建一个方法来扩展布局(或动态创建),向其中添加特定 View (在本例中为 TextViews),然后将布局重新调整为 View ,这样我就可以(以某种方式)合并它在另一个类的主布局中,如嵌套,但动态添加元素?
最佳答案
是的,您可以使用 LayoutInflater扩充现有布局的类。它会是这样的:
public static View GetLayout(final Context c){
final LayoutInflater inflater = LayoutInflater.from(c);
final View v = inflater.inflate(R.layout.activity_main, null);
//find the container where you want to insert your dynamic items
final LinearLayout placeholder = (LinearLayout) v.findViewById(R.id.linearLayout1);
//create the new textview
final TextView text = new TextView(c);
text.setText("Some text");
placeholder.addView(text, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
return v;
}
问题要求将该 View 返回给“其他类”,而其他答案是从同一个类返回的——这意味着它有一个上下文。为了从另一个类这样做,您需要像我在这里做的那样传递一个上下文,或者以其他方式(如果您想要一个实例对象,则调用构造函数等)。
关于java - 线性布局嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17581143/