自定义对话框中的按钮| Android的

时间:2013-12-17 09:44:52

标签: android android-dialog

点击“短信”按钮,我弹出一个对话框。

短信按钮仅在文本字段的长度大于0时有效。(非空...)

这是方法“短信”按钮调用onClick。

private void smsPopUp() {
        // TODO Auto-generated method stub
        final Dialog smsDialog = new Dialog(this);
        Button cancelsms = (Button)smsDialog.findViewById(R.id.smsCancel);
        smsDialog.setContentView(R.layout.sms_dialog);
        smsDialog.setTitle("To: " + numberfield.getText());

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

                smsDialog.dismiss();
            }
        });

        smsDialog.show();

    }

如果我注释掉该方法的onClick内部,则会弹出对话框,其中包含两个按钮:取消和发送。基本上,它工作..没有按钮工作。 如果我运行此代码......我会收到错误..

完整LogCat

12-17 10:37:11.500: E/(28583): file /data/data/com.nvidia.NvCPLSvc/files/driverlist.txt: not found!
12-17 10:37:11.500: I/(28583): Attempting to load EGL implementation /system/lib//egl/libEGL_tegra_impl
12-17 10:37:11.520: I/(28583): Loaded EGL implementation /system/lib//egl/libEGL_tegra_impl
12-17 10:37:11.580: I/(28583): Loading GLESv2 implementation /system/lib//egl/libGLESv2_tegra_impl
12-17 10:37:17.695: W/dalvikvm(28583): threadid=1: thread exiting with uncaught exception (group=0x411222d0)
12-17 10:37:17.700: E/AndroidRuntime(28583): FATAL EXCEPTION: main
12-17 10:37:17.700: E/AndroidRuntime(28583): java.lang.NullPointerException
12-17 10:37:17.700: E/AndroidRuntime(28583):    at com.example.dragonphone.Tabs.smsPopUp(Tabs.java:350)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at com.example.dragonphone.Tabs.onClick(Tabs.java:331)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at android.view.View.performClick(View.java:4101)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at android.view.View$PerformClick.run(View.java:17078)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at android.os.Handler.handleCallback(Handler.java:615)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at android.os.Looper.loop(Looper.java:155)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at android.app.ActivityThread.main(ActivityThread.java:5493)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at java.lang.reflect.Method.invokeNative(Native Method)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at java.lang.reflect.Method.invoke(Method.java:511)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:795)
12-17 10:37:17.700: E/AndroidRuntime(28583):    at dalvik.system.NativeStart.main(Native Method)
12-17 10:37:19.610: D/Process(28583): killProcess, pid=28583
12-17 10:37:19.610: D/Process(28583): dalvik.system.VMStack.getThreadStackTrace(Native Method)
12-17 10:37:19.610: D/Process(28583): java.lang.Thread.getStackTrace(Thread.java:599)
12-17 10:37:19.610: D/Process(28583): android.os.Process.killProcess(Process.java:944)
12-17 10:37:19.610: D/Process(28583): com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:108)
12-17 10:37:19.610: D/Process(28583): java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
12-17 10:37:19.610: D/Process(28583): java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
12-17 10:37:19.610: D/Process(28583): dalvik.system.NativeStart.main(Native Method)

我考虑过制作一个警报对话框,这显然有点容易。 但是我不确定我是否可以为“正面按钮”定制onClick ...因为“发送”onClick上会有很多代码

sms_dialog(.xml)

的屏幕截图

(只有顶部显示在对话框中(Textfield + 2按钮)。)

enter image description here

以下是完整活动代码:(Tabs.Java)

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.*;
import android.database.Cursor;
import android.graphics.*;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.TabHost.TabSpec;


public class Tabs extends Activity implements OnClickListener, OnLongClickListener{
    TabHost th;
    TabSpec specs;
    TextView numberfield;
    ListView recents;
    public String string,number;
    private List<Recent> recentCalls = new ArrayList<Recent>();
    public int counter;
    Button n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,nstar,nhash,sms,contact,call,clear,clearhistory,getinfo;

    //ImageView call, clear;
    public Vibrator vib; 
    //public String phoneNumber;
    String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabs);
        th = (TabHost)findViewById(R.id.tabhost);
        numberfield = (TextView) findViewById(R.id.etNumberField);
        n1 = (Button) findViewById (R.id.bNumber1);
        n2 = (Button) findViewById (R.id.bNumber2);
        n3 = (Button) findViewById (R.id.bNumber3);
        n4 = (Button) findViewById (R.id.bNumber4);
        n5 = (Button) findViewById (R.id.bNumber5);
        n6 = (Button) findViewById (R.id.bNumber6);
        n7 = (Button) findViewById (R.id.bNumber7);
        n8 = (Button) findViewById (R.id.bNumber8);
        n9 = (Button) findViewById (R.id.bNumber9);
        nstar = (Button) findViewById (R.id.bNumberStar);
        n0 = (Button) findViewById (R.id.bNumber0);
        nhash = (Button) findViewById (R.id.bNumberHash);
        call = (Button) findViewById (R.id.bCall);
        sms = (Button) findViewById (R.id.bSMS);


        clear = (Button) findViewById (R.id.bClear);
        contact = (Button) findViewById (R.id.bContact);
        recents = (ListView) findViewById (R.id.recentList);
        clearhistory = (Button) findViewById (R.id.bClearHistory);
        getinfo = (Button) findViewById (R.id.bGetCallDetails);



        populateRecentList();
        populateListView();
        registerClickCallback();

        th.setBackgroundColor(Color.rgb(202, 233, 252));
        //n1.getBackground().setColorFilter(new LightingColorFilter(0x000033, 0x000099));
        //sms.getBackground().setColorFilter(new LightingColorFilter(0xFFFF66, 0xFFFF00));
        vib = (Vibrator) getSystemService(VIBRATOR_SERVICE);



        n1.setOnClickListener(this);
        n2.setOnClickListener(this);
        n3.setOnClickListener(this);
        n4.setOnClickListener(this);
        n5.setOnClickListener(this);
        n6.setOnClickListener(this);
        n7.setOnClickListener(this);
        n8.setOnClickListener(this);
        n9.setOnClickListener(this);
        nstar.setOnClickListener(this);
        n0.setOnClickListener(this);
        n0.setOnLongClickListener(this);
        nhash.setOnClickListener(this);
        call.setOnClickListener(this);
        clear.setOnClickListener(this);
        clear.setOnLongClickListener(this);
        sms.setOnClickListener(this);
        contact.setOnClickListener(this);
        clearhistory.setOnClickListener(this);
        getinfo.setOnClickListener(this);


        th.setup();
        specs = th.newTabSpec("tag1");
        specs.setContent(R.id.Recents);
        specs.setIndicator("Recent Calls");
        th.addTab(specs);

        specs = th.newTabSpec("tag2");
        specs.setContent(R.id.Keypad);
        specs.setIndicator("Keypad");
        th.addTab(specs);

        specs = th.newTabSpec("tag3");
        specs.setContent(R.id.Sms);
        specs.setIndicator("SMS");
        th.addTab(specs);

        specs = th.newTabSpec("tag4");
        specs.setContent(R.id.Ratings);
        specs.setIndicator("Rates");
        th.addTab(specs);

        specs = th.newTabSpec("tag5");
        specs.setContent(R.id.Account);
        specs.setIndicator("Account");
        th.addTab(specs);


    }

    private void populateRecentList() {
         //TODO Auto-generated method stub
        recentCalls.add(new Recent("Zach", "01-12-2013", "064555246", "600"));
        recentCalls.add(new Recent("Adam", "11-12-2013", "00355563315","510"));
        recentCalls.add(new Recent("John", "03-12-2013", "00955587", "100"));
        recentCalls.add(new Recent("Jorge", "15-10-2013" , "445559585", "60"));

    }
    private void populateListView() {
        // TODO Auto-generated method stub
        ArrayAdapter<Recent> adapter = new MyRecentAdapter();
        ListView list = (ListView) findViewById(R.id.recentList);
        list.setAdapter(adapter);

    }
    private class MyRecentAdapter extends ArrayAdapter<Recent>{
        public MyRecentAdapter(){
            super(Tabs.this, R.layout.recents_view, recentCalls);

        }


    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        //Make sure we have a view to work with
        View itemView = convertView;
        if(itemView == null)
        {
            itemView = getLayoutInflater().inflate(R.layout.recents_view, parent,false);
        }
        Recent currentCall =  recentCalls.get(position);

        TextView nameText = (TextView) itemView.findViewById(R.id.tvRecentName);
        nameText.setText(currentCall.getName());

        TextView numberText = (TextView) itemView.findViewById(R.id.tvRecentNumber);
        numberText.setText(currentCall.getPn());

        TextView dateText = (TextView) itemView.findViewById(R.id.tvRecentDate);
        dateText.setText("" + currentCall.getDate());

        TextView durationText = (TextView) itemView.findViewById(R.id.tvRecentDuration);
        durationText.setText("" + currentCall.getDuration());

        return itemView;
        //      return super.getView(position, convertView, parent);

    }

}
    private void registerClickCallback() {
        // TODO Auto-generated method stub
        ListView list = (ListView) findViewById(R.id.recentList);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
                    long id) {
                // TODO Auto-generated method stub
                Recent clickedCall = recentCalls.get(position);
                String name = clickedCall.getName();
                numberfield.setText(clickedCall.getPn());
                counter = numberfield.getText().toString().length();
                String message = "Calling " + name;
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, message, duration);
                toast.show();
                call();
            }



        });

    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch(arg0.getId()){
        case R.id.bNumber1:
            numberfield.setText(numberfield.getText() + "1");
            addCheck();
            vib.vibrate(25);
            break;
        case R.id.bNumber2:
            numberfield.setText(numberfield.getText() + "2");
            addCheck();
            vib.vibrate(25);
            break;

        case R.id.bNumber3:
            numberfield.setText(numberfield.getText() + "3");
            addCheck();
            vib.vibrate(25);
            break;
        case R.id.bNumber4:
            numberfield.setText(numberfield.getText() + "4");
            addCheck();
            vib.vibrate(25);
            break;
        case R.id.bNumber5:
            numberfield.setText(numberfield.getText() + "5");
            addCheck();
            vib.vibrate(25);
            break;
        case R.id.bNumber6:
            numberfield.setText(numberfield.getText() + "6");
            addCheck();
            vib.vibrate(25);
            break;
        case R.id.bNumber7:
            numberfield.setText(numberfield.getText() + "7");
            addCheck();
            vib.vibrate(25);
            break;
        case R.id.bNumber8:
            numberfield.setText(numberfield.getText() + "8");
            addCheck();
            vib.vibrate(25);
            break;
        case R.id.bNumber9:
            numberfield.setText(numberfield.getText() + "9");
            addCheck();
            vib.vibrate(25);
            break;
        case R.id.bNumberStar:
            numberfield.setText(numberfield.getText() + "*");
            addCheck();
            vib.vibrate(25);
            break;
        case R.id.bNumber0:
            numberfield.setText(numberfield.getText() + "0");
            addCheck();
            vib.vibrate(25);
            break;
        case R.id.bNumberHash:
            numberfield.setText(numberfield.getText() + "#");
            addCheck();
            vib.vibrate(25);
            break;

        case R.id.bClear:
            String number = numberfield.getText().toString();
            if(number.length() > 0){
                String newNumber = number.substring(0, number.length()-1);
                        numberfield.setText(newNumber);
                        deleteCheck();
                        vib.vibrate(25);
            }else{
                Context context = getApplicationContext();
                CharSequence text = "The numbers are already cleared.";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }

            break;
        case R.id.bCall:
            call();

            break;
        case R.id.bContact:
             Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
              startActivityForResult(intent, 1);   
            break;
        case R.id.bClearHistory:
            recentCalls.clear();
            CharSequence text = "Your recent list has been cleared.";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(this, text, duration);
            toast.show();
            th.setCurrentTabByTag("tag1");
            break;
        case R.id.bSMS:
            if(numberfield.length() > 0){
           /* CharSequence text2 = "This function is still under construction..";
            int duration2 = Toast.LENGTH_LONG;
            Toast toast2 = Toast.makeText(this, text2, duration2);
            toast2.show();
            */
            smsPopUp();

            };
            break;
        case R.id.bGetCallDetails:
                getCallDetails();
                break;



        }
    }
    private void smsPopUp() {
        // TODO Auto-generated method stub
        final Dialog smsDialog = new Dialog(this);
        Button cancel = (Button)smsDialog.findViewById(R.id.smsCancel);
        smsDialog.setContentView(R.layout.sms_dialog);
        smsDialog.setTitle("To: " + numberfield.getText());

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

                smsDialog.dismiss();
            }
        });

        smsDialog.show();

    }



    private void deleteCheck() {
        // TODO Auto-generated method stub
        counter --;
        if(counter < 14){
            numberfield.setTextSize(25);  //Set text size when amount goes lower.
        }
        if(counter >= 14 && counter < 16){
            numberfield.setTextSize(20);  //Set text size when amount goes lower.
        }
        if(counter >= 16 && counter < 18){
            numberfield.setTextSize(18);
        }
        if(counter >= 18 && counter < 20){
            numberfield.setTextSize(16);
        }
    }
    private void addCheck() {

        // TODO Auto-generated method stub
        counter++;
        if(counter >= 14){
            numberfield.setTextSize(20);  //Set text size when amount goes higher.
            //numberfield.setMaxHeight(10);
        }
        if(counter >= 16){
            numberfield.setTextSize(18);  //Set text size when amount goes higher.
        }
        if(counter >= 18){
            numberfield.setTextSize(16);  //Set text size when amount goes higher.
        }
        if(counter >= 20){
            numberfield.setTextSize(14);  //Set text size when amount goes higher.
        }

        if(counter < 14){
            numberfield.setTextSize(25);  //Set text size when amount goes lower.
        }
        if(counter >= 14 && counter < 16){
            numberfield.setTextSize(20);  //Set text size when amount goes lower.
        }
        if(counter >= 16 && counter < 18){
            numberfield.setTextSize(18);
        }
        if(counter >= 18 && counter < 20){
            numberfield.setTextSize(16);
        }


    }
    private void getCallDetails() {
        StringBuffer sb = new StringBuffer();
        Uri contacts = CallLog.Calls.CONTENT_URI;
        Cursor managedCursor = this.getContentResolver().query(contacts, null, null, null,CallLog.Calls.DATE + " DESC LIMIT 100");
        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
        sb.append("Call Details :");
        while (managedCursor.moveToNext()) {



            String phNumber = managedCursor.getString(number);
            String callType = managedCursor.getString(type);
            String callDate = managedCursor.getString(date);
            String callDayTime = new Date(Long.valueOf(callDate)).toString();
            // long timestamp = convertDateToTimestamp(callDayTime);
            String callDuration = managedCursor.getString(duration);
            String dir = null;
            int dircode = Integer.parseInt(callType);
            switch (dircode) {
            case CallLog.Calls.OUTGOING_TYPE:
                dir = "OUTGOING";
                break;

            case CallLog.Calls.INCOMING_TYPE:
                dir = "INCOMING";
                break;

            case CallLog.Calls.MISSED_TYPE:
                dir = "MISSED";
                break;
            }
            sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " + callDayTime + " \nCall duration in sec :--- " + callDuration);
            sb.append("\n----------------------------------");


        }
        managedCursor.close();
        System.out.println(sb);
    }
private void call() {
        // TODO Auto-generated method stub
        if(numberfield.length() > 0){
        try {
               Intent callIntent = new Intent(Intent.ACTION_CALL);
                String dsPhoneNumber = "+34965063314,"; 
                // Dynamic number
                    //965063064 
             String string = numberfield.getText().toString().trim();                      
                 number = "tel:" + dsPhoneNumber + string;
                callIntent.setData(Uri.parse(number));
                startActivity(callIntent);
                //recentCalls.add(new Recent(aName, aDate, aNumber, "0"));






            } catch (ActivityNotFoundException activityException) {
                 Log.e("helloandroid dialing example", "Call failed");


            }
        }else {
            Context context = getApplicationContext();
            CharSequence text = "Please insert a phone number or choose a contact.";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }

    }
    @Override
    public boolean onLongClick(View arg0) {
        // TODO Auto-generated method stub
        switch(arg0.getId()){
        case R.id.bClear:
        if(counter != 0){
            counter = 0;
            numberfield.setTextSize(25);
        numberfield.setText("");
        vib.vibrate(100);}
        else{
            Context context = getApplicationContext();
            CharSequence text = "The numbers are already cleared.";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
        break;
        case R.id.bNumber0:

            numberfield.setText(numberfield.getText() + "+");
            addCheck();
            vib.vibrate(25);
            break;
        }
        return true;

    }
    public void onActivityResult(int reqCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK && data != null) {
            Uri uri = data.getData();

            Cursor cursor=this.getContentResolver().query(uri, null, null, null, null);

            while (cursor.moveToNext()) { 
                String contactId = cursor.getString(cursor.getColumnIndex( 
                        ContactsContract.Contacts._ID)); 
                String hasPhone = cursor.getString(cursor.getColumnIndex( 
                        ContactsContract.Contacts.HAS_PHONE_NUMBER)); 
                if (Integer.parseInt(cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { 
                    // You now have the number so now query it like this
                    Cursor phones = getContentResolver().query( 
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                            null, 
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, 
                            null, null); 
                    while (phones.moveToNext()) { 
                        String phoneNumber = phones.getString( 
                                phones.getColumnIndex( 
                                        ContactsContract.CommonDataKinds.Phone.NUMBER));  
                        numberfield.setText(phoneNumber);
                        counter = numberfield.getText().toString().length();
                        /*if(counter == 0){

                                Context context = getApplicationContext();
                                //CharSequence text = counter;
                                int duration = Toast.LENGTH_SHORT;

                                Toast toast = Toast.makeText(context, counter, duration);
                                toast.show();

                        }*/
                    } 
                    phones.close(); 


                }
            }

        }
    }
}

活跃,如果您需要,请随时提出更多信息。

1 个答案:

答案 0 :(得分:3)

反转以下陈述

Button cancel = (Button)smsDialog.findViewById(R.id.smsCancel);
smsDialog.setContentView(R.layout.sms_dialog);

应该是

smsDialog.setContentView(R.layout.sms_dialog);
Button cancel = (Button)smsDialog.findViewById(R.id.smsCancel);

您需要先将布局发送到对话框,然后初始化视图。