2015-05-23 68 views
1

我想在此ListView中實現OnItemClickListener,但是當我爲此添加代碼時,即使沒有錯誤,我的應用程序也不會運行。它在我點擊Listview項目時自動關閉。請幫助我,我是Android的初學者。我在這裏添加我的整個代碼。 我正在做藍牙設備連接代碼。如何在這段代碼中實現OnItemClickListener?

MainActivity.java

import java.util.ArrayList; 
    import java.util.Set; 

    import android.content.BroadcastReceiver; 
    import android.content.Context; 
    import android.content.DialogInterface; 
    import android.content.Intent; 
    import android.content.IntentFilter; 

    import android.graphics.Color; 
    import android.os.Bundle; 
    import android.view.View; 

    import android.app.Activity; 
    import android.app.ProgressDialog; 

    import android.widget.Button; 
    import android.widget.TextView; 
    import android.widget.Toast; 

    import android.bluetooth.BluetoothAdapter; 
    import android.bluetooth.BluetoothDevice; 

    public class MainActivity extends Activity { 
     private TextView mStatusTv; 
     private Button mActivateBtn; 
     private Button mPairedBtn; 
     private Button mScanBtn; 
     private Button ledBtn; 
     private ProgressDialog mProgressDlg; 

     private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>(); 

     private BluetoothAdapter mBluetoothAdapter; 

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

      setContentView(R.layout.activity_main); 

      mStatusTv   = (TextView) findViewById(R.id.tv_status); 
      mActivateBtn  = (Button) findViewById(R.id.btn_enable); 
      mPairedBtn   = (Button) findViewById(R.id.btn_view_paired); 
      mScanBtn   = (Button) findViewById(R.id.btn_scan); 
      ledBtn    = (Button) findViewById(R.id.led); 
      ledBtn.setOnClickListener(new View.OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        Intent i=new Intent(getApplicationContext(),Ledbuttons.class); 
        startActivity(i); 
       } 
      }); 

      mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

      mProgressDlg  = new ProgressDialog(this); 

      mProgressDlg.setMessage("Scanning..."); 
      mProgressDlg.setCancelable(false); 
      mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.dismiss(); 

        mBluetoothAdapter.cancelDiscovery(); 
       } 
      }); 

      if (mBluetoothAdapter == null) { 
       showUnsupported(); 
      } else { 
       mPairedBtn.setOnClickListener(new View.OnClickListener() {    
        @Override 
        public void onClick(View v) { 
         Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 

         if (pairedDevices == null || pairedDevices.size() == 0) { 
          showToast("No Paired Devices Found"); 
         } else { 
          ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>(); 

          list.addAll(pairedDevices); 

          Intent intent = new Intent(MainActivity.this, DeviceListActivity.class); 

          intent.putParcelableArrayListExtra("device.list", list); 

          startActivity(intent);      
         } 
        } 
       }); 

       mScanBtn.setOnClickListener(new View.OnClickListener() {     
        @Override 
        public void onClick(View arg0) { 
         mBluetoothAdapter.startDiscovery(); 
        } 
       }); 

       mActivateBtn.setOnClickListener(new View.OnClickListener() {     
        @Override 
        public void onClick(View v) { 
         if (mBluetoothAdapter.isEnabled()) { 
          mBluetoothAdapter.disable(); 

          showDisabled(); 
         } else { 
          Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 

          startActivityForResult(intent, 1000); 
         } 
        } 
       }); 

       if (mBluetoothAdapter.isEnabled()) { 
        showEnabled(); 
       } else { 
        showDisabled(); 
       } 
      } 

      IntentFilter filter = new IntentFilter(); 

      filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); 
      filter.addAction(BluetoothDevice.ACTION_FOUND); 
      filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); 
      filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 

      registerReceiver(mReceiver, filter); 
     } 


     @Override 
     public void onPause() { 
      if (mBluetoothAdapter != null) { 
       if (mBluetoothAdapter.isDiscovering()) { 
        mBluetoothAdapter.cancelDiscovery(); 
       } 
      } 

      super.onPause(); 
     } 

     @Override 
     public void onDestroy() { 
      unregisterReceiver(mReceiver); 

      super.onDestroy(); 
     } 

     private void showEnabled() { 
      mStatusTv.setText("Bluetooth is On"); 
      mStatusTv.setTextColor(Color.BLUE); 

      mActivateBtn.setText("Disable");   
      mActivateBtn.setEnabled(true); 

      mPairedBtn.setEnabled(true); 
      mScanBtn.setEnabled(true); 
      ledBtn.setEnabled(true); 
     } 

     private void showDisabled() { 
      mStatusTv.setText("Bluetooth is Off"); 
      mStatusTv.setTextColor(Color.RED); 

      mActivateBtn.setText("Enable"); 
      mActivateBtn.setEnabled(true); 

      mPairedBtn.setEnabled(false); 
      mScanBtn.setEnabled(false); 
      ledBtn.setEnabled(false); 
     } 

     private void showUnsupported() { 
      mStatusTv.setText("Bluetooth is unsupported by this device"); 

      mActivateBtn.setText("Enable"); 
      mActivateBtn.setEnabled(false); 

      mPairedBtn.setEnabled(false); 
      mScanBtn.setEnabled(false); 
     } 

     private void showToast(String message) { 
      Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); 
     } 

     private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
      public void onReceive(Context context, Intent intent) {   
       String action = intent.getAction(); 

       if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { 
        final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); 

        if (state == BluetoothAdapter.STATE_ON) { 
         showToast("Enabled"); 

         showEnabled(); 
        } 
       } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { 
        mDeviceList = new ArrayList<BluetoothDevice>(); 

        mProgressDlg.show(); 
       } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
        mProgressDlg.dismiss(); 

        Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class); 

        newIntent.putParcelableArrayListExtra("device.list", mDeviceList); 

        startActivity(newIntent); 
       } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
        BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 

        mDeviceList.add(device); 

        showToast("Found device " + device.getName()); 
       } 
      } 
     }; 

DeviceListActivity.java

import java.lang.reflect.Method; 
    import java.util.ArrayList; 

    import android.app.Activity; 
    import android.bluetooth.BluetoothDevice; 
    import android.os.Bundle; 

    import android.content.BroadcastReceiver; 
    import android.content.Context; 
    import android.content.Intent; 
    import android.content.IntentFilter; 

    import android.view.View; 
    import android.widget.ListView; 
    import android.widget.Toast; 


    public class DeviceListActivity extends Activity { 
     private ListView mListView; 
     private DeviceListAdapter mAdapter; 
     private ArrayList<BluetoothDevice> mDeviceList; 

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

      setContentView(R.layout.activity_main); 

      mDeviceList  = getIntent().getExtras().getParcelableArrayList("device.list"); 

      mListView  = (ListView) findViewById(R.id.lv_paired); 

      mAdapter  = new DeviceListAdapter(this); 

      mAdapter.setData(mDeviceList); 
      mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {    
       @Override 
       public void onPairButtonClick(int position) { 
        BluetoothDevice device = mDeviceList.get(position); 

        if (device.getBondState() == BluetoothDevice.BOND_BONDED) { 
         unpairDevice(device); 
        } else { 
         showToast("Pairing..."); 

         pairDevice(device); 
        } 
       } 
      }); 

      mListView.setAdapter(mAdapter); 

      registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)); 
     } 

     @Override 
     public void onDestroy() { 
      unregisterReceiver(mPairReceiver); 

      super.onDestroy(); 
     } 


     private void showToast(String message) { 
      Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); 
     } 

     private void pairDevice(BluetoothDevice device) { 
      try { 
       Method method = device.getClass().getMethod("createBond", (Class[]) null); 
       method.invoke(device, (Object[]) null); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 

     private void unpairDevice(BluetoothDevice device) { 
      try { 
       Method method = device.getClass().getMethod("removeBond", (Class[]) null); 
       method.invoke(device, (Object[]) null); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 

     private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() { 
      public void onReceive(Context context, Intent intent) { 
       String action = intent.getAction(); 

       if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {    
        final int state  = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); 
        final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR); 

        if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) { 
         showToast("Paired"); 
        } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){ 
         showToast("Unpaired"); 
        } 

        mAdapter.notifyDataSetChanged(); 
       } 
      } 
     }; 

    } 

DeviceListAdapter.java

import java.util.List; 

    import android.bluetooth.BluetoothDevice; 
    import android.content.Context; 

    import android.view.LayoutInflater; 
    import android.view.View; 
    import android.view.ViewGroup; 

    import android.widget.BaseAdapter; 
    import android.widget.Button; 
    import android.widget.TextView; 


    public class DeviceListAdapter extends BaseAdapter{ 
     private LayoutInflater mInflater; 
     private List<BluetoothDevice> mData; 
     private OnPairButtonClickListener mListener; 

     public DeviceListAdapter(Context context) { 
      mInflater = LayoutInflater.from(context);   
     } 

     public void setData(List<BluetoothDevice> data) { 
      mData = data; 
     } 

     public void setListener(OnPairButtonClickListener listener) { 
      mListener = listener; 
     } 

     public int getCount() { 
      return (mData == null) ? 0 : mData.size(); 
     } 

     public Object getItem(int position) { 
      return null; 
     } 

     public long getItemId(int position) { 
      return position; 
     } 

     public View getView(final int position, View convertView, ViewGroup parent) { 
      ViewHolder holder; 

      if (convertView == null) {   
       convertView   = mInflater.inflate(R.layout.list_item_device, null); 

       holder    = new ViewHolder(); 

       holder.nameTv  = (TextView) convertView.findViewById(R.id.tv_name); 
       holder.addressTv = (TextView) convertView.findViewById(R.id.tv_address); 
       holder.pairBtn  = (Button) convertView.findViewById(R.id.btn_pair); 

       convertView.setTag(holder); 
      } else { 
       holder = (ViewHolder) convertView.getTag(); 
      } 

      BluetoothDevice device = mData.get(position); 

      holder.nameTv.setText(device.getName()); 
      holder.addressTv.setText(device.getAddress()); 
      holder.pairBtn.setText((device.getBondState() == BluetoothDevice.BOND_BONDED) ? "Unpair" : "Pair"); 
      holder.pairBtn.setOnClickListener(new View.OnClickListener() {   
       @Override 
       public void onClick(View v) { 
        if (mListener != null) { 
         mListener.onPairButtonClick(position); 
        } 
       } 
      }); 

      return convertView; 
     } 

     static class ViewHolder { 
      TextView nameTv; 
      TextView addressTv; 
      TextView pairBtn; 
     } 

     public interface OnPairButtonClickListener { 
      public abstract void onPairButtonClick(int position); 
     } 
    } 

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="#060606" 
     android:orientation="vertical" 
     android:padding="@dimen/activity_vertical_margin" > 

     <TextView 
      android:id="@+id/tv_status" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:text="@string/text_bluetooth_off" 
      android:textColor="#ff0000" 
      android:textSize="17sp" /> 

     <Button 
      android:id="@+id/btn_enable" 
      android:layout_width="match_parent" 
      android:layout_height="33dp" 
      android:layout_marginTop="@dimen/activity_vertical_margin" 
      android:background="#585858" 
      android:text="@string/text_enable" /> 

     <Button 
      android:id="@+id/btn_view_paired" 
      android:layout_width="match_parent" 
      android:layout_height="33dp" 
      android:layout_marginTop="@dimen/activity_vertical_margin" 
      android:background="#585858" 
      android:enabled="false" 
      android:text="@string/text_view_paired" 
      android:textColor="#FFFFFF" /> 

     <Button 
      android:id="@+id/btn_scan" 
      android:layout_width="match_parent" 
      android:layout_height="33dp" 
      android:layout_marginTop="@dimen/activity_vertical_margin" 
      android:background="#585858" 
      android:enabled="false" 
      android:text="@string/text_scan_devices" 
      android:textColor="#FFFFFF" /> 

     <Button 
      android:id="@+id/led" 
      android:layout_width="match_parent" 
      android:layout_height="33dp" 
      android:layout_marginTop="@dimen/activity_vertical_margin" 
      android:background="#585858" 
      android:enabled="false" 
      android:text="LEDS" 
      android:textColor="#FFFFFF" /> 

     <TextView 
      android:id="@+id/TextView" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:text="List Of Devices" 
      android:textColor="#ff0000" 
      android:textSize="15sp" /> 

     <ScrollView 
      android:id="@+id/scrollView1" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" > 
     </ScrollView> 

     <ListView 
      android:id="@+id/lv_paired" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" > 
     </ListView> 

    </LinearLayout> 

list_item_device.xml

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" 
     android:paddingTop="5dp" 
     android:paddingBottom="5dp"> 

     <Button 
      android:id="@+id/btn_pair" 
      android:layout_width="100dp" 
      android:layout_height="wrap_content" 
      android:layout_alignParentRight="true" 
      android:layout_centerVertical="true" 
      android:text="Pair" 
      android:textColor="#ff4444" /> 

     <TextView 
      android:id="@+id/tv_name" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_alignTop="@+id/btn_pair" 
      android:layout_toLeftOf="@+id/btn_pair" 
      android:text="Galaxy Nexus" 
      android:textColor="#99cc00" 
      android:textSize="16sp" /> 

     <TextView 
      android:id="@+id/tv_address" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignBottom="@+id/btn_pair" 
      android:layout_alignParentLeft="true" 
      android:layout_toLeftOf="@+id/btn_pair" 
      android:text="000000000" 
      android:textColor="#ffbd21" /> 

    </RelativeLayout> 

我認爲沒有解決的問題是

  1. 當我添加一個onItemclicklistener到該應用程序無法正常工作列表顯示。

  2. 藍牙搜索結果正在填充相同的設備名稱。

  3. 查看配對設備和 掃描的設備後(我們無法訪問這些按鈕(看起來像是相同的佈局彈出屏幕)。

    任何人都請幫我解決這些問題。

在此先感謝。

+0

請同時顯示onItemClick代碼。 – NarendraJi

回答

2

你可以做這樣的 -

mListView.setOnItemClickListener(new OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View view, 
        int position, long id) { 

       Toast.makeText(getApplicationContext(), " ITEM CLICKED POSITION = "+String.valueOf(position), Toast.LENGTH_SHORT).show(); 
       } 
      }); 
+0

非常感謝 –

+0

如果有效,請接受並注意。 @RubinNellikunnathu – NarendraJi

1

看看這個代碼,它包含了如何設置與列表視圖的偵聽器檢測到單擊行和越來越副視點該行

ListView.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
        int position, long id) { 
       // TODO Auto-generated method stub 
       View row= adapter.getView(position, view, parent); 
       CheckBox box=(CheckBox) row.findViewById(R.id.checkBox1); 
       box.performClick(); 


      } 

     }); 

在適配器是你的列表視圖適配器
希望它有幫助

+0

非常感謝 –

+0

你解決了你的問題嗎? – Tony

2

你可以像這樣添加OnItemClickListener

 mListView.setOnItemClickListener(new OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
       long arg3) { { 

      Toast.makeText(getApplicationContext(),String.valueOf(arg2), Toast.LENGTH_LONG).show(); 
      } 
     });` 
+0

非常感謝 –