import android.content.Context;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParser;
import java.io.StringReader;
public class DynamicLayout {
public static View createDynamicLayout(Context context) {
// 动态生成 XML 布局字符串
String xmlLayout = "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" "
+ "android:layout_width=\"match_parent\" "
+ "android:layout_height=\"match_parent\" "
+ "android:orientation=\"vertical\">"
+ "<TextView "
+ "android:id=\"@+id/textView\" "
+ "android:layout_width=\"wrap_content\" "
+ "android:layout_height=\"wrap_content\" "
+ "android:text=\"Hello, Dynamic Layout!\" />"
+ "</LinearLayout>";
try {
// 将 XML 字符串解析为 XmlPullParser
XmlPullParser parser = Xml.newPullParser();
parser.setInput(new StringReader(xmlLayout));
// 使用 LayoutInflater 加载布局
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(parser, null);
// 获取并操作视图
TextView textView = view.findViewById(R.id.textView);
textView.setText("Dynamic Layout Loaded!");
return view;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}