为什么Listview setOnItemClickListener无法正常工作

时间:2016-04-21 03:22:53

标签: android listview onitemclicklistener

MainActivity课程中:

 public class MainActivity extends ActionBarActivity {

    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    private static final int REQUEST_ENABLE_BT = 3;

    private ListView lvMainChat;

    private EditText etMain;

    private Button btnSend;
    private String connectedDeviceName = null;
    private List<Message1> listMessages;
    private MessagesListAdapter chatArrayAdapter;
    private StringBuffer outStringBuffer;
    private BluetoothAdapter bluetoothAdapter = null;
    private ChatService chatService = null;
    private EditText result;
    final Context context = this;

    private Handler handler = new Handler(new Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                switch (msg.arg1) {
                case ChatService.STATE_CONNECTED:
                    setStatus(getString(R.string.title_connected_to,
                            connectedDeviceName));
                    chatArrayAdapter.isEmpty();
                    break;
                case ChatService.STATE_CONNECTING:
                    setStatus(R.string.title_connecting);
                    break;
                case ChatService.STATE_LISTEN:
                case ChatService.STATE_NONE:
                    setStatus(R.string.title_not_connected);
                    break;
                }
                break;

            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;

                String writemessage = new String(writeBuf);


                boolean isSelf1 = true;

                Message1 m1 = new Message1(writemessage, isSelf1);

                // Appending the message to chat list
                appendMessage(m1);



                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;

                String readMessage = new String(readBuf, 0, msg.arg1);


                boolean isSelf = false;
                Message1 m = new Message1(readMessage, isSelf);

                // Appending the message to chat list
                appendMessage(m);



                break;

            case MESSAGE_DEVICE_NAME:

                connectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(),
                        "Connected to " + connectedDeviceName,
                        Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(),
                        msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
                        .show();
                break;
            }
            return false;
        }
    });

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


        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        getWidgetReferences();
        bindEventHandler();





        Button Enskripsi = (Button) this.findViewById(R.id.btnEnskripsi);


        if (bluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available",
                    Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        result = (EditText) findViewById(R.id.etMain);
        Enskripsi.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                // get prompts.xml view
                LayoutInflater li = LayoutInflater.from(context);
                View promptsView = li.inflate(R.layout.enskripsi, null);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);

                // set prompts.xml to alertdialog builder
                alertDialogBuilder.setView(promptsView);

                final EditText ciperteks = (EditText) promptsView
                        .findViewById(R.id.cipertext);
                final EditText plainteks = (EditText) promptsView
                        .findViewById(R.id.plaintext);
                final EditText key1 = (EditText) promptsView
                        .findViewById(R.id.key1);
                final Button enskripsi = (Button) promptsView
                        .findViewById(R.id.btEnskripsi1);

                // set dialog message
                alertDialogBuilder
                        .setTitle("Enskripsi Pesan")
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        // get user input and set it to result
                                        // edit text
                                        String plaintext = plainteks.getText().toString().trim();
                                        String key=key1.getText().toString().trim();
                                        String ciper=ciperteks.getText().toString().trim();

                                        result.setText(ciperteks.getText());

                                    }
                                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();


                enskripsi.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {


                                String plaintext = plainteks.getText().toString().trim();
                                String key=key1.getText().toString().trim();

                                String enKata = "";


                                if (plaintext.isEmpty()|| key.isEmpty()) {
                                    Toast.makeText(getBaseContext(), "Silahkan Isi Textbox Yang Kosong", 1).show();
                                } else {
                                try {
                                enKata = CopyOfZIgZagCode1.RFEncryptionWork(key, plaintext);

                                } catch (Exception e) {}
                                ciperteks.setText(enKata);


                                }
                    }
                });

            }

        });




    }

    private void getWidgetReferences() {
        lvMainChat = (ListView) findViewById(R.id.lvMainChat);
        etMain = (EditText) findViewById(R.id.etMain);
        btnSend = (Button) findViewById(R.id.btnSend);


    }

    private void bindEventHandler() {



        btnSend.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String message = etMain.getText().toString();

                sendMessage(message);
            }
        });




    }

    private void appendMessage(final Message1 m) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                listMessages.add(m);

                chatArrayAdapter.notifyDataSetChanged();

                // Playing device's notification
                playBeep();
            }
        });
    }

    public void playBeep() {

        try {
            Uri notification = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
                    notification);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE_SECURE:
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data, true);
            }
            break;
        case REQUEST_CONNECT_DEVICE_INSECURE:
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data, false);
            }
            break;
        case REQUEST_ENABLE_BT:
            if (resultCode == Activity.RESULT_OK) {
                setupChat();
            } else {
                Toast.makeText(this, R.string.bt_not_enabled_leaving,
                        Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void connectDevice(Intent data, boolean secure) {
        String address = data.getExtras().getString(
                DeviceListActivity.DEVICE_ADDRESS);
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
        chatService.connect(device, secure);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent serverIntent = null;
        switch (item.getItemId()) {
        case R.id.secure_connect_scan:
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
            return true;
        case R.id.insecure_connect_scan:
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent,
                    REQUEST_CONNECT_DEVICE_INSECURE);
            return true;
        case R.id.discoverable:
            ensureDiscoverable();
            return true;
        }
        return false;
    }

    private void ensureDiscoverable() {
        if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(
                    BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    private void sendMessage(String message) {


        if (message.length() > 0) {
            byte[] send = message.getBytes();
            chatService.write(send);

            outStringBuffer.setLength(0);
            etMain.setText(outStringBuffer);
        }
    }

    private TextView.OnEditorActionListener mWriteListener = new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId,
                KeyEvent event) {
            if (actionId == EditorInfo.IME_NULL
                    && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                sendMessage(message);
            }
            return true;
        }
    };

    private final void setStatus(int resId) {
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setSubtitle(resId);
    }

    private final void setStatus(CharSequence subTitle) {
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setSubtitle(subTitle);
    }

    private void setupChat() {

        listMessages = new ArrayList<Message1>();

        chatArrayAdapter = new MessagesListAdapter(this, listMessages);
        lvMainChat.setAdapter(chatArrayAdapter);
        lvMainChat.setTextFilterEnabled(true);
        lvMainChat.setOnItemClickListener(new AdapterView.OnItemClickListener() {
               @Override
               public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                   Toast.makeText(getApplicationContext(),
                            ((TextView) view).getText(), Toast.LENGTH_SHORT).show();    

               } 
            });

        chatService = new ChatService(this, handler);

        outStringBuffer = new StringBuffer("");
    }


    @Override
    public void onStart() {
        super.onStart();

        if (!bluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            if (chatService == null)
                setupChat();
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();

        if (chatService != null) {
            if (chatService.getState() == ChatService.STATE_NONE) {
                chatService.start();
            }
        }
    }
}

AdapterList中的源代码

    public class MessagesListAdapter extends BaseAdapter {
    private Context context;
    private List<Message1> messagesItems = new ArrayList<Message1>();
            public MessagesListAdapter(Context context, List<Message1> navDrawerItems) {
        this.context = context;
        this.messagesItems = navDrawerItems;
    }

    @Override
    public int getCount() {
        return messagesItems.size();
    }

    @Override
    public Object getItem(int position) {
        return messagesItems.get(position);
    }

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

    @SuppressLint("InflateParams")
    @Override
    public View getView(int position, View convertView, final ViewGroup parent) {


        /**
         * The following list not implemented reusable list items as list items
         * are showing incorrect data Add the solution if you have one
         * */




        Message1 m = messagesItems.get(position);


        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        View rowView = mInflater.inflate(R.layout.main, parent, false);

        // Identifying the message owner
        if (m.isSelf()) {
            // message belongs to you, so load the right aligned layout
            convertView = mInflater.inflate(R.layout.list_item_message_right1,
                    null);

        } else {
            // message belongs to other person, load the left aligned layout
            convertView = mInflater.inflate(R.layout.list_item_message_left1,
                    null);



        }

        TextView lblFrom = (TextView) convertView.findViewById(R.id.lblMsgFrom);
        TextView txtMsg = (TextView) convertView.findViewById(R.id.txtMsg);
        ListView lvMainChat = (ListView) convertView.findViewById(R.id.lvMainChat);


        txtMsg.setText(m.getMessage());
        return convertView;
    }
}
list_item_message_left1.xml中的

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

    <TextView
        android:id="@+id/lblMsgFrom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12dp"
        android:textColor="@color/lblFromName"
        android:textStyle="italic" 
        android:padding="5dp"/>

    <TextView
        android:id="@+id/txtMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16dp"
        android:layout_marginRight="80dp"
        android:textColor="@color/title_gray"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:background="@drawable/bg_msg_from"/>

</LinearLayout>

list_item_message_right1.xml

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

    <TextView
        android:id="@+id/lblMsgFrom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:textColor="@color/lblFromName"
        android:textSize="12dp"
        android:textStyle="italic" />

    <TextView
        android:id="@+id/txtMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="80dp"
        android:background="@drawable/bg_msg_you"
        android:paddingBottom="5dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp"
        android:textColor="@color/white"
        android:textSize="16dp" />

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

我猜你在这里有错误: {'oct': 10} 不要将列表项转换为Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();,因为它们不是(在XML中将它们定义为(TextView))。 从适配器获取所需的字符串或使用列表项视图的子视图。 尝试即 LinearLayout