如何在使用自定义列表视图时使用意图

时间:2015-09-08 05:21:30

标签: android android-intent android-listview

如何使用自定义listview中的不同意图活动。

@SuppressLint("NewApi")
public class MainActivity extends Activity {

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

    ActionBar actionBar = getActionBar();

    // set the icon
    actionBar.setIcon(R.drawable.excel);
    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#546E7A")));

    ArrayList<Excel> list = new ArrayList<Excel>();
    list.add(new Excel("Google", "Android"));
    list.add(new Excel("Apple", "IOS"));

    ListAdapter adapter = new ListAdapter(this, list);

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

    // event handler click item of list
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
            public void onItemClick(AdapterView arg0, View arg1,
            int position, long arg3) {
                    // call new layout with intent
                Intent intent = new Intent(MainActivity.this, Apple.class);
            startActivity(intent);

        }
    });
}
}

代码只是在我点击所有项目时查看Apple.class活动,如何运行不同的活动示例:

项目Google运行Google.class

项目Apple运行Apple.class

4 个答案:

答案 0 :(得分:0)

根据您当前的代码使用

Intent intent;
if(position==0){
     intent = new Intent(MainActivity.this, Google.class);
}else if(position==1){
   intent = new Intent(MainActivity.this, Apple.class);
}
startActivity(intent);

答案 1 :(得分:0)

试试这个

   listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
            public void onItemClick(AdapterView arg0, View arg1,
            int position, long arg3) {
            switch(Position)
                {
                  case 0:
                   //Call Google Intent
                 break;
                 case 1:
                    // call new layout with intent
                Intent intent = new Intent(MainActivity.this, Apple.class);
                 startActivity(intent);
                  break;
                default:
              // default code
               break;
              }

        }
    });

答案 2 :(得分:0)

    public void onItemClick(AdapterView<?> parent, View view,
    int position, long id) {
    switch( position )
    {
      case 0:  Intent newActivity = new Intent(this, Apple.class);     
             startActivity(newActivity);
             break;
      case 1:  Intent newActivity = new Intent(this, Google.class);     
              startActivity(newActivity);
             break;


    }
 }

答案 3 :(得分:0)

使用反射来获取Class。类名必须包含packagename.Like that。

MockUserRepository