包含listview的布局,无法切换到新活动onitemclick

时间:2011-06-06 12:26:30

标签: android android-layout android-listview

我有一个listview作为mainLayout的一部分,而listview上的Onclickevent无效。任何人都可以给我指针我错了吗?

以下是代码段:

public class HostListActivity extends ListActivity {

    public ArrayList<String> deviceList;
    static LinearLayout mainLayout;
    public ListView hostListView;

   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        designLayout();
        setContentView(mainLayout);
    }

    public void designLayout() {
        mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);
        int lHeight= LinearLayout.LayoutParams.FILL_PARENT;
        int lWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
        AddHostListView(lHeight,lWidth);
    }


    private void AddHostListView(int lHeight, int lWidth) {
        deviceList = new ArrayList<String>();
        deviceList.add("abc");
        deviceList.add("efg");        
        deviceList.add("hij");

        hostListView = new ListView(this);
        hostListView.setId(android.R.id.list);

        hostListView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, deviceList));

        hostListView.setOnItemClickListener(new OnItemClickListener() { 
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {

        Intent myIntent = new Intent(v.getContext(), DirBrowserActivity.class);
            startActivity(myIntent);

            }

     });

    mainLayout.addView(hostListView, new LinearLayout.LayoutParams (lHeight,lWidth));

 }

// DirBrowserActivity类

公共类DirBrowserActivity扩展了Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {    
    super.onCreate(savedInstanceState);
       TextView tv = new TextView(this);
       tv.setText("Hello, DirBrowse View");
       setContentView(tv);
}

}

2 个答案:

答案 0 :(得分:1)

扩展ListActivity,但不使用此类中的任何功能。我注意到这与不使用OnItemClickListener有关。简单地改变:

public class HostListActivity extends ListActivity {

要  public class HostListActivity extends Activity {

会有所帮助。

答案 1 :(得分:0)

你应该把这段代码

registerForContextMenu(getListView());

将适配器设置到列表视图后,如果要为项目添加上下文菜单。如果您只想在项目的单击上创建smth,则需要使用此方法:

@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
    }

希望这有帮助。