ListView setOnClickListener

时间:2014-08-13 19:34:40

标签: android listview

我按下listView中的列表项。我如何从列表视图项目转到我的另一个活动? 请帮我理解如何解决这个问题。

以下是我的代码:

package com.example.list;

import java.util.ArrayList;


public class MainActivity extends ListActivity {

ListView listView;
Context context;
ArrayList prgmList;

public static int[] prgmImage = { R.drawable.a_2, R.drawable.a_2,
        R.drawable.a_2, R.drawable.a_2, R.drawable.a_2, R.drawable.a_2,
        R.drawable.a_2, R.drawable.a_2

};
public static String[] prgmNameList = { "Let Us C", "c++", "JAVA", "Jsp",
        "Microsoft .Net", "Android", "PHP", "Jquery", "JavaScript" };

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

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
    setContentView(R.layout.activity_main);

    context = this;
    listView = (ListView) findViewById(R.id.listView1);
    listView.setAdapter(new CustomAdapter(this, prgmNameList, prgmImage));

}

}

3 个答案:

答案 0 :(得分:1)

你必须实施

OnItemClickListener

到您的活动并将其设置为listView:

public class MainActivity extends Activity implements OnItemClickListener {

...

...

listview.setOnItemClickListener(this);

然后你会得到一个新方法:

@Override
public void onItemClick(AdapterView<?> arg0, View view, int pos, long id) {

    Log.e(TAG, "Pos: " + pos);

}

在这里你得到被舔项目的位置

答案 1 :(得分:0)

嗨,为了解决您的问题,您只需要调用此方法onListItemClick。此方法显示您选择的女士行,您也可以设置一些意图。

protected void onListItemClick (ListView l, View v, int position, long id)
{
    Toast.makeText(this, "Clicked row " + position, Toast.LENGTH_SHORT).show();
    //go to another activity
    Intent intent = new Intent();
    intent.setAction(this, SecondActivity.class);
    startActivity(intent);
}

答案 2 :(得分:0)

只需将OnItemClickListener设置为ListView,如:

final Context context = this;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        intent.putExtra("position", position);
        intent.setAction(context, OtherActivity.class);
        startActivity(intent);
    }
});