Gak*_*ak2 3 android android-layout
嗨,我正在尝试使用inflater以编程方式添加布局(这是一个简单的TextView).膨胀视图的父级是ScrollView中的RelativeLayout.我的问题是我正在尝试使用params.addRule和view.setLayoutParams()将新视图放在其标题下(在RelativeLayout中),但是我得到了一个转发异常:11-12 13:06:57.360: E/AndroidRuntime(10965): java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams,即使是父视图view显然是一个RelativeLayout.有什么想法吗?
我在想它是因为RelativeLayout嵌套在一个scrollview中,但我不明白为什么它会这样做,因为我添加的视图的直接父级是RelativeLayout.
_innerLayout = (RelativeLayout) findViewById(R.id.innerRelativeLayout);
LayoutInflater inflater = (LayoutInflater)this.getLayoutInflater();
View view = inflater.inflate(R.layout.comments, _innerLayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.commentsHeader);
view.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)
如果使用非null View作为root inflate()方法,则View返回的实际将是View作为方法中的根传递.所以,你的情况view是_innerLayout RelativeLayout它有一个父ScrollView,这是一个扩展FrameLayout(这将解释LayoutParams).
因此要么使用当前的inflate方法,要么在返回的视图中查找视图:
View view = inflater.inflate(R.layout.comments, _innerLayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.commentsHeader);
(view.findViewByid(R.id.theIdOfTextView)).setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)
或者使用其他版本inflate()(不附加充气视图并手动将其与适当的一起添加LayoutParams):
View view = inflater.inflate(R.layout.comments, _innerLayout, false);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.commentsHeader);
view.setLayoutParams(params);
_innerLayout.addView(view);
Run Code Online (Sandbox Code Playgroud)