开发者

Layout containing listview, unable to switch to new activity onitemclick

开发者 https://www.devze.com 2023-03-11 13:27 出处:网络
I am having a listview as part of a mainLayout and Onclickevent on listview is not working. Can anybody give me pointer where I am wrong?

I am having a listview as part of a mainLayout and Onclickevent on listview is not working. Can anybody give me pointer where I am wrong?

Here's the code snippet:

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>();
        dev开发者_开发问答iceList.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 class

public class DirBrowserActivity extends Activity{

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

}


You extend ListActivity but you do not use any feature from this class. I have noticed that this correlates with not working OnItemClickListener. Simply changing:

public class HostListActivity extends ListActivity {

to public class HostListActivity extends Activity {

will help.


You should put this code

registerForContextMenu(getListView());

after setting an adapter to your listview, if you want to add a context menu to your items. If you just want to make smth on an item's click, you need to ovverride this method:

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

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消