【问题标题】:Can a ListView be displyed programatically without an XML layout?可以在没有 XML 布局的情况下以编程方式显示 ListView 吗?
【发布时间】:2011-03-27 09:23:08
【问题描述】:

我有一个活动,我想在其中显示一个带有 2 个简单字符串项的 ListView。我尝试了两种不同的方式(w/xml 布局和 w/o xml 布局)-两种方式我都添加了 2 个项目,但最终这些项目仅在创建 w/xml 布局列表的版本中可见。这是为什么呢?

xml 布局,list_view_custom_layout.xml 包含:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
   <ListView android:id="@+id/ListView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

使用 XML 的代码(并且运行良好)执行以下操作:

activity.setContentView(R.layout.list_view_custom_layout); //this must be done here
listView=(ListView)activity.findViewById(R.id.ListView);

除了上面两行之外,不使用 XML 的代码是相同的 它这样做(这似乎应该是等效的):

LinearLayout customLayout=new LinearLayout(activity);
//customLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
    ViewGroup.LayoutParams.FILL_PARENT,
    ViewGroup.LayoutParams.FILL_PARENT);
customLayout.setLayoutParams(layout);


ListView listView=new ListView(activity);
customLayout.addView(listView,new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.FILL_PARENT,
    LinearLayout.LayoutParams.WRAP_CONTENT));

不是 2 等价物,如果是,为什么要添加项目(通过适配器) 仅显示第一种方法(其中使用 xml 布局)? 谢谢

【问题讨论】:

  • 使用 Hierarchy Viewer 检查这两种情况,看看哪里出错了。

标签: android xml listview layout


【解决方案1】:

试试这个..

public class VersionActivity extends Activity {

    LinearLayout linearLayout;
    ListView listView;
    ArrayAdapter<String> aR;
    String[] str = new String[] { "item1", "item2", "item3", "item4", "item5",
            "item6" };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        linearLayout = new LinearLayout(this);
        listView = new ListView(this);
        aR = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, str);
        listView.setAdapter(aR);
        linearLayout.addView(listView);
        setContentView(linearLayout);
    }
}

【讨论】:

  • 这会抛出这个异常Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 2011-10-05
  • 2011-03-12
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多