4
我已经能够使用XML中的静态定义的片段中的TextView元素。但是当我尝试以动态/编程方式创建它们时,我没有看到任何显示内容。我已经创建了一个我遇到的问题的简单例子。将TextView对象动态添加到片段中
这一个工程,我看到屏幕更新。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.hello_world, container, false);
TextView tv = (TextView)v.findViewById(R.id.text);
tv.setText("Fragment #" + mNum);
tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
return v;
}
这一个不起作用。 XML文件diagtextvertical.xml就是这样的:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
</LinearLayout>
代码如下。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
//good View v = inflater.inflate(R.layout.diaglist, container, false);
View v = inflater.inflate(R.layout.diagverticaltext, container, false);
mycontainer = container;
LinearLayout l = (LinearLayout)inflater.inflate(R.layout.diagverticaltext, container, false);
TextView tv = new TextView(container.getContext());
tv.setText("Testing...");
l.addView(tv);
tv = new TextView(container.getContext());
tv.setText("Testing1...");
l.addView(tv);
tv = new TextView(container.getContext());
tv.setText("Testing2...");
l.addView(tv);
return v;
}
我试过用getActivity()代替container.getContext(),但没有运气。我不清楚如何将布局映射到实际视图实例 - 这与在Activity中执行此操作不同。
我的问题还有第二部分。我的实际目标是基于轮询数据异步更新视图,所以我有一个问题是如何在我自己的回调中调用ViewGroup和inflater。
我已经解决了这个问题,通过定义一个
yladsr
2012-04-17 22:04:01