我不能使用OnClicListener复选框

时间:2015-08-17 18:32:45

标签: android xml checkbox onclicklistener

我不能在我的复选框中使用OnClicListener。当我使用OnClicListener

时,我的应用程序崩溃了

SDCardImagesActivity.java

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class SDCardImagesActivity extends Activity {


private ImageAdapter imageAdapter;
private ArrayList<File> imagenesSeleccionadas;
private File[] imagenes;

private static final String DIRECCION_IP = "http://192.168.1.127";


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

    WifiManager wifiManager ;
    wifiManager (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);


    File directorios;
    directorios = Environment.getExternalStorageDirectory();
    directorios = getFolder(directorios, "WhatsApp");
    directorios = getFolder(directorios, "Media");
    directorios = getFolder(directorios, "WhatsApp Images");
    imagenes = directorios.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String filename) {
            return filename.endsWith(".jpg");
        }
    });
    directorios = null;


    imagenesSeleccionadas = new ArrayList<>();
    final GridView gridView = (GridView) findViewById(R.id.Grid);
    Button transfer = (Button) findViewById(R.id.btnTransfer);
    final CheckBox seleccionarTodo=(CheckBox)findViewById(R.id.checkbox);

    if (imagenes != null){
        imageAdapter = new ImageAdapter(SDCardImagesActivity.this,imagenes);
        gridView.setAdapter(imageAdapter);
        gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE);
        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                File file = imagenes[position];
                if (imagenesSeleccionadas.contains(file)) {
                    imagenesSeleccionadas.remove(file);
                    imageAdapter.getView(position, view, parent).setBackgroundColor(Color.WHITE);
                } else {
                    imagenesSeleccionadas.add(file);
                    imageAdapter.getView(position, view, parent).setBackgroundColor(Color.BLUE);
                }
                file = null;
            }
        });

        seleccionarTodo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (seleccionarTodo.isChecked()) {
                    seleccionarTodo.setText("Seleccionar Todo");
                    Toast.makeText(SDCardImagesActivity.this, "Desmarcado", Toast.LENGTH_SHORT).show();
                    for (int i = 0; i < imageAdapter.getCount(); i++) {
                        if (!gridView.isItemChecked(i)) {
                            gridView.setItemChecked(i, true);
                            imagenesSeleccionadas.add((File) imageAdapter.getItem(i));
                        }
                    }
                } else {
                    seleccionarTodo.setText("Deseleccionar Todo");
                    Toast.makeText(SDCardImagesActivity.this, "Marcado", Toast.LENGTH_SHORT).show();
                    for (int i = 0; i < imageAdapter.getCount(); i++) {
                        if (gridView.isItemChecked(i)) {
                            gridView.setItemChecked(i, false);
                            imagenesSeleccionadas.clear();
                        }
                    }
                }
            }
        });



        transfer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!imagenesSeleccionadas.isEmpty()) {

                    Intent service = new Intent(getApplicationContext(), HttpSendingService.class);

                    try
                    {
                        OutputStreamWriter fout = new OutputStreamWriter(openFileOutput(".config", Context.MODE_PRIVATE));
                        fout.write(DIRECCION_IP);
                        fout.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    for (File f : imagenesSeleccionadas){
                        service.setData(Uri.parse(f.getAbsolutePath()));
                        getApplicationContext().startService(service);
                    }

                } else {
                    Toast.makeText(SDCardImagesActivity.this, "Ninguna imagen seleccionada", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }else{
        Toast.makeText(SDCardImagesActivity.this, "Images array is null", Toast.LENGTH_SHORT).show();
    }
}

private File getFolder(File file, String nextFolderName){
    File nextFolder = null;
    File[] fileList;
    if (file.isDirectory()){
        fileList = file.listFiles();
        for (File f:fileList){
            if (f.isDirectory()){
                if (f.getName().equals(nextFolderName)){
                    nextFolder = f;
                }
            }
        }
    }
    return nextFolder;
}


}

清单:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".SDCardImagesActivity"
        android:label="@string/app_name">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".HttpSendingService"
        android:exported="false"/>

</application>

最后,activity.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layaut"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <GridView xmlns:android="http://schemas.android.com/apk/res/android"
        android:clickable="true"
        android:id="@+id/Grid"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="2dp"
        android:verticalSpacing="3dp"
        android:horizontalSpacing="3dp"
        android:numColumns="3"
        android:stretchMode="columnWidth"
        android:gravity="center"
        android:layout_above="@+id/btnTransfer"
        android:drawSelectorOnTop="true"
        android:layout_below="@+id/checkBox" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Trasmitir Imágenes"
        android:id="@+id/btnTransfer"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:capitalize="words"
        android:clickable="true"/>

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Seleccionar Todo"
        android:id="@+id/checkBox"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:clickable="true"/>
</RelativeLayout>

多数民众赞成。那么,为什么我不能使用我的复选框没有错误或应用程序崩溃?

1 个答案:

答案 0 :(得分:2)

查看您的XML。你应该发布你的LogCat,但我敢打赌你得到一个与复选框相关的NullPointerException。

<CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Seleccionar Todo"
        android:id="@+id/checkBox"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:clickable="true"/>

请注意android:id="@+id/checkBox" checkBox的大写字母为“B”。

在您的代码中,您正在寻找带有小写“b”的“复选框”。

final CheckBox seleccionarTodo=(CheckBox)findViewById(R.id.checkbox);

看起来应该是这样的

final CheckBox seleccionarTodo=(CheckBox)findViewById(R.id.checkBox);