在我的应用程序中,我有简单的布局,以填充任何具有类结构的数据。添加项目后,我想将此布局添加到滚动视图中。向scrollview添加布局是成功的但我无法将数据设置为自定义布局。例如,这是我设置数据的自定义布局:
tile.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/drop_shadow">
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="30dp" android:minHeight="100dp" android:background="#eee">
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="New Text"
android:id="@+id/username"/>
</LinearLayout>
</LinearLayout>
班级数据结构:
public class SubjectStructure {
public String username;
public String topic;
public String description;
public String avatar;
public String sender;
public Integer grade;
public Integer type;
public String date;
}
现在我想填充tile.xml并将其添加到下面的布局中:
fragment_home.xml:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#F1F1F1">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/scrollView1">
</LinearLayout>
</ScrollView>
我的代码是这样的: public View onCreateView(LayoutInflater inflater,ViewGroup容器, Bundle savedInstanceState){
View rootView = inflater.inflate( R.layout.fragment_home, container, false);
scrollView = (LinearLayout) rootView.findViewById ( R.id.scrollView1 );
for(SubjectStructure SS: G.subject_items){
LinearLayout newLL = new LinearLayout( G.context );
TextView newTV = new TextView( G.context );
newTV.setText ( SS.topic );
newLL.addView(newTV);
LayoutInflater in = (LayoutInflater) G.context.getSystemService(G.context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.tile, null);
scrollView.addView(view);
}
return rootView;
}
在此代码中,我可以将tile.xml
添加到fragment_home.xml
。但是我无法将文本SS.topic
设置为tile.xml
。 SS.topic
不为空且有数据。如何解决这个问题?
答案 0 :(得分:1)
你肯定缺少的是
scrollView.addView(newLL);
每次迭代。约
LayoutInflater in = (LayoutInflater) G.context.getSystemService(G.context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.tile, null);
scrollView.addView(view);
我不确定它的目的。您在每次迭代时创建tile
的新实例,但您对其内容不执行任何操作。在次要方面,您已经有了LayoutInflater。您不需要在每次迭代时向系统请求一个,使用您获得的那个作为参数。
答案 1 :(得分:0)
按如下方式更改代码:
for(SubjectStructure SS: G.subject_items){
LayoutInflater in = (LayoutInflater) G.context.getSystemService(G.context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.tile, null);
TextView textUserName=(TextView) view.findViewById(R.id.username);
textUserName.setText(SS.topic);
scrollView.addView(view);
}