【问题标题】:declare listview in main class findviewbyid not working在主类 findviewbyid 中声明 listview 不起作用
【发布时间】:2013-05-09 08:43:17
【问题描述】:

我制作了一个自定义 listview。现在我想为 listview 添加 onitemclick 方法,但为此需要在 主类 中声明 listview >。我的列表视图的xml代码如下。

   <ListView
   android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView8"
   >

</ListView> 

如果我以 android:id="@+id/list" 之类的格式更改 id,那么我的应用程序崩溃了。 所以建议我该怎么做才能解决它?

【问题讨论】:

    标签: android xml android-listview


    【解决方案1】:

    如果我以 android:id="@+id/list" 之类的格式更改 id,那么我的 应用崩溃

    因为如果您在 xml 中使用 @+id/android:list id 声明了 ListVIew,那么您将需要使用 android.R.id.list 来初始化 ListView 实例。在主类中这样做:

    ListView listview = (ListView) findViewById(android.R.id.list);
    

    或者,如果您正在扩展 ListActivity,那么您也可以使用 getListView() 方法将 ListView 实例初始化为

    ListView listview = Current_Activity_Name.this..getListView();  
    

    【讨论】:

      【解决方案2】:

      只需使用findViewById(android.R.id.list); 即可获得ListView

      【讨论】:

        【解决方案3】:

        你必须声明

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>
        

        那么你必须这样做

        ListView v = (ListView)findViewById(R.id.listView1)
        

        然后

        v.setOnItemClick(new onItemClickListener(){
        
             public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
        
             }
        
        });
        

        我认为你不应该使用"@android:id/list"

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-05-16
          • 2015-08-13
          • 1970-01-01
          • 2017-02-12
          • 1970-01-01
          • 2021-04-17
          相关资源
          最近更新 更多