【问题标题】:Adding TextView object dynamically to a Fragment将 TextView 对象动态添加到 Fragment
【发布时间】:2012-04-17 03:33:45
【问题描述】:

当它们在我的 XML 中静态定义时,我已经能够使用 Fragment 中的 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 和充气器。

【问题讨论】:

  • 我已经通过在我的 XML 中将

标签: android android-fragments dynamic textview


【解决方案1】:

我是 android 开发新手,但我认为您应该在 onCreateView 中返回 l 而不是 v,或者您应该将 TextViews 添加到 v

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多