Android应用程序开发扩展了一个java类

时间:2015-07-05 12:02:13

标签: java class android-studio

我正在创建一个应用程序,需要扩展主Activity中的类ListActivity以使用setListAdapter()函数。但是当我用ActionBarActivity替换ListActivity时,即使没有检测到任何错误,当我运行应用程序时它也会显示

  

由于错误无法运行

如何解决此问题。

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.app.ListActivity;
import android.widget.ListView;

import java.util.List;

public class MainActivity extends ActionBarActivity {

DataSource dataSource;
ListView lv;
List<people> peoples;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dataSource = new DataSource(this);
    dataSource.open();

    peoples = dataSource.getPeople();

    if (peoples.size() == 0) {
        insertData();
        peoples = dataSource.getPeople();
    }

    refreshDisplay();



}
protected void onPause(){
    super.onPause();
    dataSource.close();
}

protected void onResume(){
    super.onResume();
    dataSource.open();
}

private void insertData(){
    people pl = new people();

    pl.setName("Uditha");
    pl.setTp("123");
    pl = dataSource.insert(pl);
}

public void refreshDisplay(){


    ArrayAdapter<people> adapter = new itemVievHelper(this, peoples);

    lv = (ListView) findViewById(R.id.listView);
    lv.setAdapter(adapter);

    //ArrayAdapter<people> adapter = new ArrayAdapter<people>(this, android.R.layout.simple_list_item_1, peoples);

}

1 个答案:

答案 0 :(得分:0)

您无需延长ListViewActivity即可使用ListView。只需将ListView小部件添加到您的XML布局,为此小部件提供ID并从Activity访问它。例如:

在XML布局中:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

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

</RelativeLayout>

然后,您可以在ListView

中访问此Activity
public class MainActivity extends ActionBarActivity {   
  private ListView myListView;

  @Override   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myListView = (ListView) findViewById(R.id.my_list_view);
    myListView.setAdapter(...) // set your adapter here
    // perform another operations on myListView   
  } 
}