在自定义ListView上OnItemClick的问题

时间:2012-10-29 19:03:08

标签: android listview android-arrayadapter onitemclicklistener

我正在为自定义对象使用自定义ListView和自定义ArrayAdapter。我用一个xml文件中的解析数据填充我的ListView。我可以使用这些数据填充ListView,但我想根据点击的项目切换到不同的活动。我可以用

来表示
  

int position

单击了哪个项目但是如何检索单击按钮的名称?

我的代码:

  /**
     * Setup
     * */ 
    @SuppressWarnings("unchecked")
    private void setup() throws IOException {

        device_array = new ArrayList<Device>();

        //-----------------ACTIONBAR------------------------------------
        //activates the default ActionBar
        ActionBar actionBar = getActionBar();
        actionBar.show();
        // set the app icon as an action to go home
        actionBar.setDisplayHomeAsUpEnabled(true);       

        //-------------------INTENT--------------------------------------
        //get data from Intent
        Intent intent = getIntent();
        Name = intent.getStringExtra("Projectname");
        IP = intent.getStringExtra("RouterIP");
        URL = intent.getStringExtra("URL");
        Port = intent.getStringExtra("Port");

        //-------------------TEXTVIEWS+LISTVIEW---------------------------------------
        nameproject = (TextView)findViewById(R.id.nameproject);
        nameproject.setText("Projektname: "+Name);
        routerip = (TextView)findViewById(R.id.routerip);
        routerip.setText("KNX/IP-Router-Adresse: "+IP);
        port = (TextView)findViewById(R.id.port);
        port.setText(":"+Port);
        url = (TextView)findViewById(R.id.url);
        url.setText("URL: "+URL);

        //Fill ListView
        display_listview();

        devices = (ListView)findViewById(R.id.deviceList);
        adapter = new DeviceAdapter(this, 
                R.layout.listviewitem_device, device_array);

        //add a view which is shown if the ListView is empty
        devices.setEmptyView(findViewById(R.id.empty_list_view));

        //Click on item in listview
        devices.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                      int position, long id) {

                Intent i = new Intent(ProjectView.this, OnOff.class);    
                i.putExtra("Uniqid","From_ProjectView_Activity");
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }   
        });
        devices.setAdapter(adapter); 

        //-------------------- READ ARRAYLIST-------------------------------
    }

 /**
     * Insert Controls
     * */ 
    @SuppressWarnings("unchecked")
    private void display_listview() {

        //------------------ READ ARRAYLIST--------------------------------
        //read ArrayList which is saved local
        //change path to non-root folder
        String filePath = context.getFilesDir().getPath().toString()+"/"+Name;
        Log.d("FilestreamfromFolder", "Filepath:"+filePath+ " Projektname:"+Name);
        File f = new File(filePath);
        try
        {
            FileInputStream fileIn = new FileInputStream(f);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            XML = (ArrayList<Datapoint>) in.readObject();
            Log.d("XML",XML.toString());
            in.close();
            fileIn.close();
        } catch(IOException ioe)
        {
            ioe.printStackTrace();
            return;
        } catch(ClassNotFoundException c)
        {
            Log.d("FILESTREAM", ".Datapoint class not found.");
            c.printStackTrace();
            return;
        }

      //------------------ FILL DEVICE ARRAY FROM XML--------------------------------
        for (int i=0; i<XML.size(); i++) {  
            if (XML.get(i).getDptID().contains(ValueTemp)) {
                Datapoint d = XML.get(i);       
                device_array.add(new Device(d.getName().toString(), R.drawable.temperature_5));  
                Log.d("Temperature", d.getName().toString()+" added");
            }
        }
        for (int i=0; i<XML.size(); i++) {  
            if (XML.get(i).getDptID().contains(ValueLux)) {
                Datapoint d = XML.get(i);               
                device_array.add(new Device(d.getName().toString(), R.drawable.brightness));
                Log.d("Brightness", d.getName().toString()+" added");
            }
        }   
        for (int i=0; i<XML.size(); i++) {  
            if (XML.get(i).getDptID().contains(PercentScaling)) {
                Datapoint d = XML.get(i);           
                device_array.add(new Device(d.getName().toString(), R.drawable.lamp));
                Log.d("Dimmer", d.getName().toString()+" added");
            }
        }
        for (int i=0; i<XML.size(); i++) {
            //check XML file for datapoint 1.001 which demontrates a on/off switch
            if (XML.get(i).getDptID().contains(OnOff)) {
                Datapoint d = XML.get(i); 
                device_array.add(new Device(d.getName().toString(), R.drawable.lamp_switch)); 
                Log.d("OnOFF", d.getName().toString()+" added");
            }
        }
    }   

我的数据点类:

package XMLParser;

import java.io.Serializable;

public class Datapoint implements Serializable{

/**
* 
*/
private static final long serialVersionUID = 4917183601569112207L;

private String stateBased;
  private String name;
  private String priority;
  private String mainNumber;
  private String groupadress;
  private String dptID;

  public Datapoint(){
  }

  public String getMainNumber() {
    return mainNumber;
  }

  public void setMainNumber(String mainNumber) {
    this.mainNumber = mainNumber;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getStateBased() {
    return stateBased;
  }

  public void setStateBased(String stateBased) {
    this.stateBased = stateBased;
  }

  public String getPriority() {
    return priority;
  }

  public void setPriority(String priority) {
    this.priority = priority;
  }

  public String getGroupadress() {
    return groupadress;
  }

  public void setGroupadress(String group) {
    this.groupadress = convert_groupadress(group);
  }

  public String getDptID() {
    return dptID;
  }

  public void setDptID(String dptID) {
    this.dptID = dptID;
  }

  @Override
  public String toString() {
    return "[[" + this.stateBased + "] ["+ this.name + "] [" + this.mainNumber + "]" + " [" + this.dptID
        + "] [" + this.priority + "] [" + this.groupadress + " ]]";
  }

  public String convert_groupadress(String groupadress) {
    String groupaddress ="";
    int grpadr = Integer.parseInt(groupadress); 
    int first = grpadr / 2048;
    int first_res = grpadr-(first*2048);

    int second = first_res / 256;
    int second_res = first_res-(second*256);

    int third = second_res / 1; 
    //int third_res = second_res-(third*32);

    groupaddress = Integer.toString(first) +"/"+ Integer.toString(second) + "/"+ Integer.toString(third);

    return groupaddress;
  }

}

3 个答案:

答案 0 :(得分:1)

在适配器上调用getItem(int position)方法将获得该位置的DataPoint,因此请将onItemClick方法更改为:

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

    DataPoint point = (DataPoint) parent.getAdapter().getItem(position);
    String pointName = point.getName();
    // TODO: Launch an activity with that name or something.
} 

答案 1 :(得分:0)

我这样解决了:

//Click on item in listview
        devices.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                      int position, long id) {

                if(device_array.get(position).getResImage()==R.drawable.brightness){
                    Intent i0 = new Intent(ProjectView.this, Brightness.class);    
                    i0.putExtra("Uniqid","From_ProjectView_Activity");
                    i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(i0);
                }

                if(device_array.get(position).getResImage()==R.drawable.temperature_5){
                    Intent i0 = new Intent(ProjectView.this, Temperature.class);    
                    i0.putExtra("Uniqid","From_ProjectView_Activity");
                    i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(i0);
                }

                if(device_array.get(position).getResImage()==R.drawable.lamp){
                    Intent i0 = new Intent(ProjectView.this, Dimmer.class);    
                    i0.putExtra("Uniqid","From_ProjectView_Activity");
                    i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(i0);
                }

                if(device_array.get(position).getResImage()==R.drawable.lamp_switch){
                    Intent i0 = new Intent(ProjectView.this, OnOff.class);    
                    i0.putExtra("Uniqid","From_ProjectView_Activity");
                    i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(i0);
                }
            }   
        });

答案 2 :(得分:0)

使用视图,您正在使用列表视图中的数据进行充气。 因为我正在使用textview。

这里使用的是什么,

TextView tv = (TextView) v.findViewById(R.id.contacts_name);
String savedname = tv.getText().toString();

这里v是我们在方法

中得到的参数
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
{ // do something
}