@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);
    setTitle("Second Activity");

    Intent inIntent = getIntent();
    String calc = inIntent.getStringExtra("calc");
    final double first = inIntent.getDoubleExtra("first", 0);
    final double second = inIntent.getDoubleExtra("second", 0);
    final double result;
    Button ret = (Button) findViewById(R.id.ret);

    if (calc.equals("plus")) result = Double.parseDouble(String.format("%.3f", first + second));
    else if (calc.equals("minus"))
      result = Double.parseDouble(String.format("%.3f", first - second));
    else if (calc.equals("multiply"))
      result = Double.parseDouble(String.format("%.3f", first * second));
    else if (calc.equals("divider"))
      result = Double.parseDouble(String.format("%.3f", first / second));
    else result = 0;

    ret.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Intent outIntent = new Intent(getApplicationContext(), MainActivity.class);
            outIntent.putExtra("result", result);
            setResult(RESULT_OK, outIntent);
            finish();
          }
        });
  }
  public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case 1:
        mBtn.setTextColor(Color.RED);
        return true;
      case 2:
        mBtn.setTextColor(Color.GREEN);
        return true;
      case 3:
        mBtn.setTextColor(Color.BLUE);
        return true;
      case 4:
        Toast.makeText(this, "번역했다.", Toast.LENGTH_SHORT).show();
        return true;
      case 5:
        Toast.makeText(this, "필기 인식했다.", Toast.LENGTH_SHORT).show();
        return true;
      case 100:
        Toast.makeText(this, "회전했다 치고.", Toast.LENGTH_SHORT).show();
        return true;
      case 101:
        Toast.makeText(this, "크기 변경 했다 치고.", Toast.LENGTH_SHORT).show();
        return true;
    }

    return true;
  }
  public MapView(Context ctx, boolean allowNetAccess, int mode) {
    super(ctx);

    Display display;

    this.allowNetAccess = allowNetAccess;

    geoUtils = new GeoUtils(mode);

    setBackgroundColor(0xFF555570);
    display = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    scrWidth = display.getWidth();
    scrHeight = display.getHeight();
    setMinimumHeight(scrWidth);
    setMinimumWidth(scrHeight);
    tileWidth = (int) Math.ceil(scrWidth / 256.0) + 1;
    tileHeight = (int) Math.ceil(scrHeight / 256.0) + 1;
    gestureDetector = new GestureDetector(ctx, new GestureListener());

    zoomOutButton = new Button(ctx);
    zoomOutButton.setText("  -  ");
    zoomOutButton.setOnClickListener(this);

    zoomInButton = new Button(ctx);
    zoomInButton.setText("  +  ");
    zoomInButton.setOnClickListener(this);

    updateUI(true);
    addView(zoomOutButton);
    addView(zoomInButton);
  }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.rss_reader);
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    btnManage = (Button) findViewById(R.id.btn_manage);
    btnBrowse = (Button) findViewById(R.id.btn_browse);
    btnRefresh = (Button) findViewById(R.id.btn_refresh);
    btnSearch = (Button) findViewById(R.id.btn_search);

    btnManage.setOnClickListener(this);
    btnBrowse.setOnClickListener(this);
    btnRefresh.setOnClickListener(this);
    btnSearch.setOnClickListener(this);

    txtSearch = (EditText) findViewById(R.id.txt_search);

    init();

    boolean hasUpdate = false;
    try {
      hasUpdate = getIntent().getExtras().getBoolean("rss_update");
    } catch (NullPointerException e) {
      e.printStackTrace();
    }

    if (hasUpdate) {
      rssFeed = dbQuery.getUpdatedRssFeed();
      updateListView();
    } else loadData(null, true, false, true);
  }
示例#5
0
  // Reaction to the menu selection
  @Override
  public boolean onMenuItemSelected(int featureId, MenuItem item) {
    //        Intent i;
    mItem = item.getItemId();
    openCode = mItem;
    //        fileRegExp=".*";

    fileRequest = item.getItemId();
    switch (item.getItemId()) {
      case mNewDB:
        i = new Intent(this, getText.class);
        startActivityForResult(i, mNewDB);
        //			getDBname();
        return true;
      case mCopy:
        fileName = CreateShopDatabase.DATABASE_NAME;
        confirmButton.performClick();

        //                i = new Intent(this, getText.class);
        //                startActivityForResult(i, mCopy);

        //			getDBname();
      case mXMLImp:
        confirmButton.setVisibility(View.VISIBLE);
        fileRequest = item.getItemId();
        //                fileRegExp=".*";

        fileRegExp = "(?i)hs2_.*\\.xml";
        //                fileRegExp="hs2.*\\.xml";
        getDir(sdcard, "(?i)hs2_.*\\.xml");
        //                getDir(sdcard, "hs2.*\\.xml");
        //                getDir(sdcard, ".*");

        //                i = new Intent(this, getText.class);
        //                startActivityForResult(i, mXMLImp);

        return true;
      case mExport:
        fileRegExp = ".*";
        getDir(sdcard, "/");
        confirmButton.setVisibility(View.VISIBLE);
        /*
                        fileRequest = item.getItemId();
                        fileName=nameDialog("Export to:","")
                        i = new Intent(this, getText.class);
        */
        //                startActivityForResult(i, mExport);

        // context.deleteDatabase(DATABASE_NAME);
        // http://stackoverflow.com/questions/4406067/how-to-delete-sqlite-database-from-android-programmatically
        return true;

      case mQuit:
        return true;
    }
    return super.onMenuItemSelected(featureId, item);
  }
 @Override
 public void onClick(View inButton) {
   boolean isErr = false;
   if (mTitle.getText().toString().length() == 0) {
     mTitle.setError("Required");
     mTitle.setEms(10);
     isErr = true;
   }
   if (mDesc.getText().toString().length() == 0) {
     mDesc.setActivated(true);
     mDesc.setError("Required");
     isErr = true;
   }
   if (inButton.getId() == openWeb.getId()) web.setVisibility(View.VISIBLE);
   else if (inButton.getId() == mAvail.getId())
     startActivity(new Intent(this, CheckActivity.class));
   else if (inButton.getId() == mBack.getId()) finish();
   else if (inButton.getId() == mSub.getId()) {
     AlertDialog.Builder al = new AlertDialog.Builder(this);
     if (isErr) return;
     else
       al.setTitle("Continue?")
           .setIcon(R.drawable.ornament)
           .setMessage("Your listing is going to be submitted to your chosen category.")
           .setPositiveButton(
               "OK",
               new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface d, int x) {
                   payment = new ArrayList<String>();
                   if (mCard.isChecked()) payment.add("Card");
                   if (mCheck.isChecked()) payment.add("Check");
                   if (mOnline.isChecked()) payment.add("Online");
                   if (mCash.isChecked()) payment.add("Cash");
                   //			Toast.makeText(getApplicationContext(), payment.toString(),
                   // Toast.LENGTH_LONG).show();
                   Intent intent = new Intent(getApplicationContext(), StartActivity.class);
                   intent.putExtra("Payment", payment);
                   intent.putExtra("Category", mChosenCategory);
                   intent.putExtra("Title", mTitle.getText().toString());
                   intent.putExtra("Price", mPrice.getText().toString());
                   intent.putExtra("Description", mDesc.getText().toString());
                   intent.putExtra("Location", mLocation.getText().toString());
                   intent.putExtra("Photo", jpegData);
                   startActivity(intent);
                 }
               })
           .setNegativeButton(
               "Cancel",
               new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface d, int x) {}
               })
           .show();
   } else
     startActivityForResult(
         new Intent(this, com.lightbox.android.camera.activities.Camera.class), REQ);
 }
 public void setNextButton() {
   Button meatButton = (Button) findViewById(R.id.meatToppingsButton);
   meatButton.setOnClickListener(
       new View.OnClickListener() {
         @Override
         public void onClick(View v) {
           Intent intent = new Intent(MeatToppingsActivity.this, NameActivity.class);
           intent.putExtra("size", size);
           intent.putExtra("numVeggieToppings", numVeggieToppings);
           intent.putExtra("numMeatToppings", numMeatToppings);
           startActivity(intent);
         }
       });
 }
示例#8
0
文件: Add.java 项目: nidebo/LowCost
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add);
    // almacenando valores ingresados por el usuario
    nombre = (EditText) findViewById(R.id.edit_name);
    ciudad = (EditText) findViewById(R.id.edit_city);
    // declarando a los botones
    final Button agregar = (Button) findViewById(R.id.yes_b);
    // final Button cancelar = (Button)findViewById(R.id.btnCancelar);
    // acción cuando le dan click al boton agregar
    agregar.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            // se realiza el intento de enviar los datos de un activity a otro, de Registro a
            // Salida.
            // Intent intent = new Intent(RegistroLibroActivity.this, SalidaResultado.class);
            // Bundle b = new Bundle();
            // almacenamiento temporal para poder usarlo en otro activity
            String bnombre = String.valueOf(nombre.getText());
            String bciudad = String.valueOf(ciudad.getText());

            nombre.setText("");
            ciudad.setText("");

            // llamada al metodo para insertar los datos.
            insertPrso(bnombre, bciudad);
            // datos que seran vistos en el otro main
            // b.putString("T", btitulo);
            // b.putString("A", bautor);
            // b.putString("I", bidioma);
            // b.putString("B", baño);
            // intent.putExtras(b);
            // startActivity(intent);
          }
        });
    // acción cuando le dan click al boton agregar
    // cancelar.setOnClickListener(new View.OnClickListener() {
    //   public void onClick(View v) {
    //     titulo.setText(" ");
    //   autor.setText(" ");
    // idioma.setText(" ");
    // año.setText(" ");
    // }
    // });
  }
示例#9
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    c = this;
    preferences = PreferenceManager.getDefaultSharedPreferences(c);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.gpu_sgx540);

    gpuCurrent = readFile(Constants.GPU_SGX540);
    seekGpu = (SeekBar) findViewById(R.id.seek_gpu);

    gpu = Arrays.asList(153, 307, 384);
    seekBar(gpu.size() - 1, gpu.indexOf(gpuCurrent));

    /*else{
    seekGpu.setEnabled(false);
    seekIva.setEnabled(false);
    TextView ns = (TextView)findViewById(R.id.not_supported);
    ns.setVisibility(View.VISIBLE);
    }*/
    preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    curGpuTxt = (TextView) findViewById(R.id.current_gpu);
    maxGpuTxt = (TextView) findViewById(R.id.max_gpu);
    minGpuTxt = (TextView) findViewById(R.id.min_gpu);

    mhz = getResources().getString(R.string.mhz);
    current = getResources().getString(R.string.current);
    max = getResources().getString(R.string._max);
    min = getResources().getString(R.string._min);
    curGpuTxt.setText(current + ": " + (gpuCurrent) + mhz);
    maxGpuTxt.setText(max + ": " + gpu.get(2) + mhz);
    minGpuTxt.setText(min + ": " + gpu.get(0) + mhz);

    Button cancel = (Button) findViewById(R.id.cancel);
    cancel.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            finish();
          }
        });
  }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.receiver);

    final Button cancelbtn = (Button) findViewById(R.id.ButtonCancel);
    // cancelbtn.setEnabled(false);
    cancelbtn.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            // streamtask.cancel(true);
            finish();
          }
        });

    try {
      Intent intent = getIntent();
      String action = intent.getAction();
      String type = intent.getType();

      if ((!(Intent.ACTION_SEND.equals(action))) || (type == null)) {
        throw new RuntimeException("Unknown intent action or type");
      }

      if (!("text/plain".equals(type))) {
        throw new RuntimeException("Type is not text/plain");
      }

      String extra = intent.getStringExtra(Intent.EXTRA_TEXT);
      if (extra == null) {
        throw new RuntimeException("Cannot get shared text");
      }

      final DownloadStreamTask streamtask = new DownloadStreamTask(this);

      //	Once created, a task is executed very simply:
      streamtask.execute(extra);

    } catch (Exception e) {
      Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
    }
  }
    @Override
    public DownloadStreamTask(Context _c) {
      mContext = new WeakReference<Context>(_c);
      // dialog = new ProgressDialog(myact.this);

      text1 = (TextView) findViewById(R.id.textView1);

      Button cancelbtn = (Button) findViewById(R.id.ButtonCancel);
      cancelbtn.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              // Do something in response to button click
              cancel(true);
            }
          });

      cancelbtn.setEnabled(true);
    }
 /**
  * 控制表情区和软键盘的显示
  *
  * @param isShowKeyboard
  * @param isSwitch
  */
 private void controlKeyboardOrExpr(boolean isShowKeyboard, boolean isSwitch) {
   if (isSwitch) {
     if (!isShowKeyboard) {
       mIsExprShow = true;
       mIsSoftKeyboardShow = false;
       mImm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
       mUiHandler.postDelayed(
           new Runnable() {
             @Override
             public void run() {
               mExpressionWidgt.setVisibility(View.VISIBLE);
             }
           },
           100);
       mExprBtn.setBackgroundResource(R.drawable.selector_s_chat_keyboard);
     } else {
       mIsExprShow = false;
       mIsSoftKeyboardShow = true;
       mExpressionWidgt.setVisibility(View.GONE);
       mExprBtn.setBackgroundResource(R.drawable.selector_s_chat_expressions);
       mImm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
     }
   } else {
     if (isShowKeyboard) {
       mIsExprShow = false;
       mIsSoftKeyboardShow = true;
       mExpressionWidgt.setVisibility(View.GONE);
       mImm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
     } else {
       if (mIsSoftKeyboardShow) {
         mIsSoftKeyboardShow = false;
         mImm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
       } else {
         mIsExprShow = false;
         mExpressionWidgt.setVisibility(View.GONE);
       }
     }
     mExprBtn.setBackgroundResource(R.drawable.selector_s_chat_expressions);
   }
 }
 /**
  * onClick
  *
  * <p>extracts the relai that was clicked, and asks the ipx to open then close the corresponding
  * relai
  */
 @Override
 public void onClick(View view) {
   Ipx800Control ipx = context.getIpx();
   if (view instanceof Button) {
     Button button = (Button) view;
     // Log.d(TAG, "hit the button " + button.getHint()+ "id = "+button.getId());
     try {
       int port2trigger = Integer.parseInt("" + button.getHint());
       // Log.d(TAG, "would trigger ipx out "+port2trigger);
       try {
         ipx.set(port2trigger, true);
         ipx.set(port2trigger, false);
       } catch (Exception e) {
         Toast.makeText(context, "error:" + e, Toast.LENGTH_LONG).show();
       }
     } catch (NumberFormatException e) {
       // ok, we hit a special button....
       if (button.getId() == R.id.servernameValue) context.callSettings();
       else if (button.getHint().equals("fill_me")) context.callSettings();
       // else Log.e(TAG,"unknown button code: "+button.getHint());
     }
   }
 }
示例#14
0
        public void onServiceConnected(ComponentName name, IBinder service) {
          loggingService = ((GpsLoggingService.GpsLoggingBinder) service).getService();
          GpsLoggingService.SetServiceClient(GpsMainActivity.this);

          Button buttonSinglePoint = (Button) findViewById(R.id.buttonSinglePoint);

          buttonSinglePoint.setOnClickListener(GpsMainActivity.this);

          if (Session.isStarted()) {
            if (Session.isSinglePointMode()) {
              SetMainButtonEnabled(false);
            } else {
              SetMainButtonChecked(true);
              SetSinglePointButtonEnabled(false);
            }

            DisplayLocationInfo(Session.getCurrentLocationInfo());
          }

          // Form setup - toggle button, display existing location info
          ToggleButton buttonOnOff = (ToggleButton) findViewById(R.id.buttonOnOff);
          buttonOnOff.setOnCheckedChangeListener(GpsMainActivity.this);
        }
示例#15
0
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.settings);
   this.setTitle(R.string.setting);
   sp = PreferenceManager.getDefaultSharedPreferences(this);
   edit = sp.edit();
   Button widgettheme = (Button) findViewById(R.id.widgettheme);
   Button settime = (Button) findViewById(R.id.settime);
   Button save = (Button) findViewById(R.id.set_save);
   nc = (CheckBox) findViewById(R.id.nightcheck);
   rs = (CheckBox) findViewById(R.id.ringswitch);
   widgettheme.setOnClickListener(
       new View.OnClickListener() {
         @Override
         public void onClick(View Button) {
           AlertDialog.Builder ad =
               new AlertDialog.Builder(Settings.this)
                   .setTitle("选择颜色?")
                   .setItems(
                       color,
                       new DialogInterface.OnClickListener() {
                         @Override
                         public void onClick(DialogInterface p1, int p2) {
                           edit.putInt("widgetTextColor", colori[p2]);
                           edit.commit();
                         }
                       });
           ad.show();
         }
       });
   settime.setOnClickListener(
       new View.OnClickListener() {
         @Override
         public void onClick(View Button) {
           Intent set = new Intent(Settings.this, Settime.class);
           startActivity(set);
           return;
         }
       });
   save.setOnClickListener(
       new View.OnClickListener() {
         public void onClick(View Button) {
           save();
           return;
         }
       });
   nc.setChecked(sp.getBoolean("nightmode", false));
   if (sp.getBoolean("timewrong", false) == true) {
     rs.setChecked(false);
     rs.setClickable(false);
   }
 }
示例#16
0
 private void updateUI(boolean enabled) {
   if (useOverlay.m_zoom >= 17) {
     zoomInButton.setEnabled(false);
     zoomOutButton.setEnabled(true & enabled);
   } else if (useOverlay.m_zoom <= 3) {
     zoomInButton.setEnabled(true & enabled);
     zoomOutButton.setEnabled(false);
   } else {
     zoomInButton.setEnabled(enabled);
     zoomOutButton.setEnabled(enabled);
   }
 }
示例#17
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mDbHelper = new ShopDbAdapter(this);
    File sdcardPath = Environment.getExternalStorageDirectory();
    sdcard = sdcardPath.toString();
    /*
            File rootPath= getApplicationContext().getFilesDir()
            root=rootPath.toString();
    */

    setContentView(R.layout.fileslist);
    confirmButton = (Button) findViewById(R.id.file_confirm_button);
    myPath = (TextView) findViewById(R.id.path);

    //        root=this.getFilesDir();
    //        getDir(sdcard);
    getDir(root, fileRegExp);

    registerForContextMenu(getListView());
    final Context xx = this;
    ListView list = getListView();
    confirmButton.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View view) {
            confirmButton.setVisibility(View.GONE);

            String value = nameDialog("Export to:", "");
            if (value != null && value.length() > 0) {
              fileName = selectFile + "/" + value + ".abb"; // TODO: Check for dir
              cpDb(fileName);
            }

            // context.deleteDatabase(DATABASE_NAME);
            // http://stackoverflow.com/questions/4406067/how-to-delete-sqlite-database-from-android-programmatically
            return;
          }
        });
  }
示例#18
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btnFind = (Button) findViewById(R.id.button1);
    txtName = (EditText) findViewById(R.id.editText1);

    btnFind.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            // TODO Auto-generated method stub
            String name = txtName.getText().toString();
            if (name.equals("")) return;
            Intent i = new Intent(MainActivity.this, ResultActivity.class);
            Bundle b = new Bundle();
            b.putString("name", name);
            i.putExtras(b);
            startActivityForResult(i, RESULT_ACT_CODE);
          }
        });
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.profile);
    findViews();
    /*Select Category work */
    final String[] categories = getIntent().getStringArrayExtra("Options");
    ArrayAdapter<String> catadapt;
    catadapt = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
    mCatSpin.setAdapter(catadapt);
    mCatSpin.setOnItemSelectedListener(
        new OnItemSelectedListener() {
          public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
            mChosenCategory = categories[pos];
          }

          public void onNothingSelected(AdapterView<?> parent) {}
        });
    /*Availability selection work*/
    mAvail = (Button) findViewById(R.id.editavail);
    mAvail.setOnClickListener(this);
    /*Submit/Back button work*/
    mSub = (Button) findViewById(R.id.submitbutton);
    mSub.setOnClickListener(this);
    mBack.setOnClickListener(this);
    /*Web View & Camera uploader work*/
    openCam.setOnClickListener(this);
    openWeb.setOnClickListener(this);
    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("http://www.monkbananas.com/uploader/index.php");
    // ------Everything below this line was found on StackOverflow--------------------
    web.setWebChromeClient(
        new WebChromeClient() {
          @Override
          public boolean shouldOverrideUrlLoading(WebView v, String url) {
            web.loadUrl(url);
            return true;
          }
          // The undocumented magic method override
          // Eclipse will swear at you if you try to put @Override here
          // For Android 3.0+
          public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
          }

          // For Android 3.0+
          public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
          }

          // For Android 4.1
          public void openFileChooser(
              ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
          }
        });
  }
示例#20
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = getIntent();
    final String ID = intent.getStringExtra("ID");
    final String name = intent.getStringExtra("Name");
    final ActionBar actionBar = getSupportActionBar();

    setContentView(R.layout.individual_colour_change_layout);

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    ColH = settings.getInt("houCol" + ID, getResources().getColor(R.color.clokH));
    ColM = settings.getInt("minCol" + ID, getResources().getColor(R.color.clokM));
    ColS = settings.getInt("secCol" + ID, getResources().getColor(R.color.clokS));
    String currentTitle = name + ": " + getString(R.string.chsColour);
    if (actionBar != null) {
      actionBar.setTitle(currentTitle);
      actionBar.setDisplayUseLogoEnabled(false);
    }

    draw();

    Button reset = (Button) findViewById(R.id.reset);
    reset.setOnClickListener(
        v -> {
          Editor editor = settings.edit();
          ColH = IndividualColourChange.this.getResources().getColor(R.color.clokH);
          ColM = IndividualColourChange.this.getResources().getColor(R.color.clokM);
          ColS = IndividualColourChange.this.getResources().getColor(R.color.clokS);
          editor.putInt("houCol" + ID, ColH);
          editor.putInt("minCol" + ID, ColM);
          editor.putInt("secCol" + ID, ColS);
          editor.apply();
          IndividualColourChange.this.draw();
        });

    ImageView colPickH = (ImageView) findViewById(R.id.colorHou);
    colPickH.setClickable(true);
    colPickH.setOnClickListener(
        v -> {
          ColorSelectorDialog dlg =
              new ColorSelectorDialog(
                  context,
                  color -> {
                    ColH = color;
                    Editor editor = settings.edit();
                    editor.putInt("houCol" + ID, ColH);
                    editor.apply();
                    draw();
                  },
                  ColH);
          dlg.setTitle(IndividualColourChange.this.getString(R.string.hHandCol));
          dlg.show();
        });

    ImageView colPickM = (ImageView) findViewById(R.id.colorMin);
    colPickM.setClickable(true);
    colPickM.setOnClickListener(
        v -> {
          ColorSelectorDialog dlg =
              new ColorSelectorDialog(
                  context,
                  color -> {
                    ColM = color;
                    Editor editor = settings.edit();
                    editor.putInt("minCol" + ID, ColM);
                    editor.apply();
                    draw();
                  },
                  ColM);
          dlg.setTitle(IndividualColourChange.this.getString(R.string.mHandCol));
          dlg.show();
        });

    ImageView colPickS = (ImageView) findViewById(R.id.colorSec);
    colPickS.setClickable(true);
    colPickS.setOnClickListener(
        v -> {
          ColorSelectorDialog dlg =
              new ColorSelectorDialog(
                  context,
                  color -> {
                    ColS = color;
                    Editor editor = settings.edit();
                    editor.putInt("minCol" + ID, ColS);
                    editor.apply();
                    draw();
                  },
                  ColS);
          dlg.setTitle(IndividualColourChange.this.getString(R.string.sHandCol));
          dlg.show();
        });
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gatt_services_characteristics);

    final Intent intent = getIntent();
    mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
    mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);

    // Sets up UI references.
    mConnectionState = (TextView) findViewById(R.id.connection_state);
    // is serial present?
    isSerial = (TextView) findViewById(R.id.isSerial);

    msgEdit = (EditText) findViewById(R.id.editText);
    returnText = (TextView) findViewById(R.id.returnText);

    sendButton = (Button) findViewById(R.id.sendButton);
    //        timeButton = (Button) findViewById(R.id.timeButton);

    sendButton.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            if (characteristicReady) {
              StringBuffer sb = new StringBuffer("m");
              sb.append(msgEdit.getText()).append("\n");

              sendMessage(sb.toString());
            }
          }
        });

    //        timeButton.setOnClickListener(new View.OnClickListener() {
    //
    //            @Override
    //            public void onClick(View v) {
    //                if (characteristicReady) {
    //                    StringBuffer sb = new StringBuffer("t");
    //                    Date now = new Date();
    //                    sb.append(DATE_FORMAT.format(now)).append("\n");
    //
    //                    sendMessage(sb.toString());
    //                }
    //            }
    //        });

    infoButton = (ImageView) findViewById(R.id.infoImage);
    infoButton.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            iascDialog();
          }
        });

    mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
    mSurfaceHolder = mSurfaceView.getHolder();
    mSurfaceHolder.addCallback(new MyHolder());

    mPaint = new Paint();
    // 画笔的粗细
    mPaint.setStrokeWidth(5.0f);

    getActionBar().setTitle(mDeviceName);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
    bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
  }
示例#22
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    try {
      mSharedPreferences = Prefs.getSharedPreferences(this);
    } catch (NullPointerException e) {
      if (BuildConfig.DEBUG) {
        Log.w("[" + TAG + "]", "mSharedPreferences == NullPointerException :" + e.getMessage());
      }
    }

    mSharedPreferences.registerOnSharedPreferenceChangeListener(this);

    if (Prefs.getThemeType(this) == false) {
      mThemeId = R.style.AppTheme_Light;
      setTheme(mThemeId);
    } else {
      mThemeId = R.style.AppTheme_Dark;
      setTheme(mThemeId);
    }

    // Eula.showDisclaimer( this );
    Eula.showEula(this, getApplicationContext());

    mActionBar = getActionBar();
    if (mActionBar != null) {
      mActionBar.setDisplayHomeAsUpEnabled(false);
      mActionBar.setDisplayShowHomeEnabled(true);
      mActionBar.setDisplayShowTitleEnabled(true);
    } else {
      if (BuildConfig.DEBUG) {
        Log.w("[" + TAG + "]", "mActionBar == null");
      }
    }

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
      this.setTitle(extras.getString("dir") + " :: " + getString(R.string.app_name));
    } else {
      this.setTitle(" :: " + getString(R.string.app_name));
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tvDisplay = (TextView) findViewById(R.id.tvDisplay);

    bRename = (Button) findViewById(R.id.bRename);
    bSettings = (Button) findViewById(R.id.bSettings);
    bHelp = (Button) findViewById(R.id.bHelp);
    bExit = (Button) findViewById(R.id.bExit);

    bRename.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            Intent openAndroidFileBrowser = new Intent("com.scto.filerenamer.ANDROIDFILEBROWSER");
            openAndroidFileBrowser.putExtra("what", "renamer");
            openAndroidFileBrowser.putExtra("theme", mThemeId);
            startActivity(openAndroidFileBrowser);
          }
        });

    bSettings.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            Intent openPreferencesActivity = new Intent("com.scto.filerenamer.PREFERENCESACTIVITY");
            startActivity(openPreferencesActivity);
          }
        });

    bHelp.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            HelpDialog helpDialog = new HelpDialog();
            helpDialog.show(fm, "dlg_help");
          }
        });

    bExit.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            ExitDialog exitDialog = new ExitDialog();
            exitDialog.show(fm, "dlg_exit");
          }
        });

    /*
    ChangeLog cl = new ChangeLog( this );
    if( cl.firstRun() )
    {
    	cl.getLogDialog().show();
    }
    */
    init();
  }
示例#23
0
 public void SetSinglePointButtonEnabled(boolean enabled) {
   Button buttonSinglePoint = (Button) findViewById(R.id.buttonSinglePoint);
   buttonSinglePoint.setEnabled(enabled);
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    // locks the screen in portrait mode
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.downloader);
    mtext = (TextView) findViewById(R.id.mtext);
    progress_text = (TextView) findViewById(R.id.progress_text);
    progress_download = (ProgressBar) findViewById(R.id.progress_download);
    // resume capability

    paused = false;
    resume_pause = (Button) findViewById(R.id.resume);

    // Create and launch the download thread
    downloadThread = new DownloadThread(this);
    downloadThread.start();

    // Create the Handler. It will implicitly bind to the Looper
    // that is internally created for this thread (since it is the UI thread)
    handler = new Handler();

    resume_pause.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            if (!paused) {
              paused = true;
              resume_pause.setText("Resume");
              // writeProgress(completed_downloads,total_files_to_download);
              downloadThread.requestStop();
              downloadThread = null;

            } else {
              resume_pause.setText("Pause");
              paused = false;

              initial_value = readProgress()[0];
              final_value = links.size();

              for (int i = initial_value; i < links.size(); i++) {
                downloadThread = new DownloadThread(download_photos.this);
                downloadThread.start();
                downloadThread.enqueueDownload(
                    new DownloadTask(
                        links.get(i), path, i + 1, links.size(), download_photos.this));
              }
            }
          }
        });

    // load preferences for this activity
    mPrefs = getSharedPreferences("COMMON", MODE_PRIVATE);

    // This declaration is solely meant for reading the checkbox preference for downloading high res
    // pics.
    SharedPreferences dl_prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    // The global variable is set after reading the  checkbox preference.
    dl_high_res_pics = dl_prefs.getBoolean("download_high_res", false);

    // load fb access token and its expiry values
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);

    if (access_token != null) {
      facebook.setAccessToken(access_token);
    }
    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }

    // get friend_name and album_name from the intent which started this activity
    Intent starting_intent = getIntent();
    album_id = starting_intent.getStringExtra("id");
    album_name = starting_intent.getStringExtra("name");
    friend_name = starting_intent.getStringExtra("friend_name");

    // real album and friend name may contain characters not suitable for file names.
    // regex pattern includes most of the invalid characters in file names
    legal_album_name = album_name.replaceAll("[.\\\\/:*?\"<>|]?[\\\\/:*?\"<>|]*", "");
    legal_friend_name = friend_name.replaceAll("[.\\\\/:*?\"<>|]?[\\\\/:*?\"<>|]*", "");

    // initialise the directory structure for download
    path =
        new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                + "/"
                + getText(R.string.app_name)
                + "/"
                + legal_friend_name
                + "/"
                + legal_album_name);
    if (dl_high_res_pics)
      path = new File(path.toString() + "/" + getText(R.string.folder_name_high_res));

    resume_file = new File(path, "resume.txt");
    // implements actions to done after receiving json object
    class meRequestListener extends BaseRequestListener {
      @Override
      public void onComplete(String response, Object state) {
        try {
          Log.i(TAG, response);
          json = Util.parseJson(response);

          // photos are in the form of a json array
          child = json.getJSONArray("data");

          int total = child.length();

          // contains links to photos
          links = new ArrayList<String>(total);

          // adds link to each photo to our list after replacing the "https" from url
          // DownloadManager does not support https in gingerbread
          for (int i = 0; i < total; i++) {
            photo_json = child.getJSONObject(i);

            if (dl_high_res_pics) {
              JSONArray image_set = photo_json.getJSONArray("images");

              // highest resolution picture has the index zero in the images jsonarray
              JSONObject highest_res_pic = image_set.getJSONObject(0);
              String http_replaced =
                  highest_res_pic.getString("source").replaceFirst("https", "http");
              links.add(i, http_replaced);
            } else {
              // source property of the json object points to the photo's link
              String http_replaced = photo_json.getString("source").replaceFirst("https", "http");
              links.add(i, http_replaced);
            }
          }

          download_photos.this.runOnUiThread(
              new Runnable() {
                public void run() {
                  //	mytask = new DownloadImageTask();
                  //	mytask.execute(links);
                  // start downloading using asynctask
                  // new DownloadImageTask().execute(links);
                  // downloadThread.setPath(path);
                  // downloadThread.setWholeTasks(links.size());
                  if (resume_file.exists()) {

                    initial_value = readProgress()[0];
                    final_value = links.size();
                    // case if the task is already completed
                    if (initial_value == final_value) {
                      completed = true;
                      resume_pause.setVisibility(View.GONE);

                      progress_download.setMax(final_value);
                      progress_download.setProgress(0); // bug in progress bar
                      progress_download.setProgress(initial_value);

                      progress_text.setText("Completed.");
                      mtext.setText(
                          getText(R.string.download_textview_message_1)
                              + " "
                              + path.toString()
                              + ". ");

                    }

                    // case if some of the photos are already downloaded
                    else {
                      progress_download.setMax(links.size());
                      // progress_download.setProgress(0);	//bug in progress bar
                      progress_download.setProgress(initial_value);

                      // N.B if i= initial_value -1, then one image will be downloaded again. so to
                      // save cost we start with i = initial_value
                      for (int i = initial_value; i < links.size(); i++) {
                        mtext.setText(
                            getText(R.string.download_textview_message_1)
                                + " "
                                + path.toString()
                                + ". ");
                        // downloadThread.setRunningTask(i + 1);
                        downloadThread.enqueueDownload(
                            new DownloadTask(
                                links.get(i), path, i + 1, final_value, download_photos.this));
                      }
                    }
                  }

                  // case if the task is entirely new task
                  else {
                    for (int i = 0; i < links.size(); i++) {
                      mtext.setText(
                          getText(R.string.download_textview_message_1)
                              + " "
                              + path.toString()
                              + ". ");
                      // downloadThread.setRunningTask(i + 1);
                      downloadThread.enqueueDownload(
                          new DownloadTask(
                              links.get(i), path, i + 1, links.size(), download_photos.this));
                    }
                  }
                }
              });
        } catch (JSONException ex) {
          Log.e(TAG, "JSONEXception : " + ex.getMessage());
        }
      }
    }

    // makes asynchronous request to facebook graph api
    // the actions to be performed after receiving json response is implemented above

    Bundle parameters = new Bundle();

    // facebook returns only 25 photos when limit is not specified.
    parameters.putString("limit", max_photos_in_album);
    if (!completed) mAsyncRunner.request(album_id + "/photos", parameters, new meRequestListener());

    if (!facebook.isSessionValid()) {
      facebook.authorize(
          this,
          permissions,
          new DialogListener() {

            // save fb access token and its expiry values to prefernces of this activity
            @Override
            public void onComplete(Bundle values) {
              SharedPreferences.Editor editor = mPrefs.edit();
              editor.putString("access_token", facebook.getAccessToken());
              editor.putLong("access_expires", facebook.getAccessExpires());
              editor.commit();
            }

            @Override
            public void onFacebookError(FacebookError error) {
              Log.e(TAG, "Facebook Error : " + error.getMessage());
            }

            @Override
            public void onError(DialogError e) {
              Log.e(TAG, e.getMessage());
            }

            @Override
            public void onCancel() {
              // do nothing LOL :-)
            }
          });
    }
  }
示例#25
0
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
      View view = convertView;
      if (view == null) {
        LayoutInflater inflater =
            (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.content_list_item, null);
      }
      TextView titleTextView = (TextView) view.findViewById(R.id.list_item_title);
      TextView stateTextView = (TextView) view.findViewById(R.id.list_item_state);
      TextView downTextView = (TextView) view.findViewById(R.id.list_item_downbar);
      Button downloadButton = (Button) view.findViewById(R.id.list_item_download_button);
      Button uploadButton = (Button) view.findViewById(R.id.list_item_upload_button);

      LocationInfo info = mInfoList.get(position);
      String titleText = info.title;
      String stateText = "";

      if (titleText.length() > 30) titleText = titleText.substring(0, 28) + "...";

      synchronized (mLoaderMap) {
        if (mLoaderMap.containsKey(info.title)) {
          LoaderState loader = mLoaderMap.get(info.title);
          if (loader.state < 100) stateText = String.format(Locale.ENGLISH, "%d%%", loader.state);
          else if (loader.state == 100) stateText = String.format(Locale.ENGLISH, "Done!");
          else stateText = String.format(Locale.ENGLISH, "Failed!");
        }
      }

      if (info.localVersion < 0) titleText += " (?)";
      else {
        if (info.localModified)
          titleText += String.format(Locale.ENGLISH, " (v. %d+)", info.localVersion);
        else titleText += String.format(Locale.ENGLISH, " (v. %d)", info.localVersion);
      }

      String mapFile = NavigineApp.Settings.getString("map_file", "");
      if (mapFile.equals(info.archiveFile)) {
        titleTextView.setTypeface(null, Typeface.BOLD);
        view.setBackgroundColor(Color.parseColor("#590E0E"));
      } else {
        titleTextView.setTypeface(null, Typeface.NORMAL);
        view.setBackgroundColor(Color.BLACK);
      }

      titleTextView.setText(titleText);
      stateTextView.setText(stateText);

      if (info.localModified) {
        downloadButton.setVisibility(View.GONE);
        uploadButton.setVisibility(View.VISIBLE);
        downTextView.setText("Version is modified. Upload?");
      } else if (info.serverVersion > info.localVersion) {
        downloadButton.setVisibility(View.VISIBLE);
        uploadButton.setVisibility(View.GONE);
        String downText =
            String.format(Locale.ENGLISH, "Version available: %d", info.serverVersion);
        downTextView.setText(downText);
      } else {
        downloadButton.setVisibility(View.INVISIBLE);
        uploadButton.setVisibility(View.GONE);
        downTextView.setText("Version is up to date");
      }

      downloadButton.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              startDownload(position);
            }
          });

      uploadButton.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              startUpload(position);
            }
          });

      return view;
    }
 @Override
 public void onHideInputView() {
   if (!mIsExprShow && mExprBtn != null) {
     mExprBtn.setBackgroundResource(R.drawable.selector_s_chat_expressions);
   }
 }
示例#27
0
  @Override
  public void onClick(View v) {
    TextView txtManageLabel, txtBrowseLabel, txtRefreshLabel, txtSearchLabel;
    txtManageLabel = (TextView) findViewById(R.id.txt_manage_label);
    txtBrowseLabel = (TextView) findViewById(R.id.txt_browse_label);
    txtRefreshLabel = (TextView) findViewById(R.id.txt_refresh_label);
    txtSearchLabel = (TextView) findViewById(R.id.txt_search_label);
    txtSearch.addTextChangedListener(
        new TextWatcher() {
          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {
            new AsyncTask<String, Void, ArrayList<RssItem>>() {
              @Override
              protected ArrayList<RssItem> doInBackground(String... params) {
                return dbQuery.searchRssItem(params[0]);
              }

              @Override
              protected void onPostExecute(ArrayList<RssItem> result) {
                rssList.clear();
                rssList.addAll(result);
                rssAdapter.config().notifyDataSetChanged();
              }
            }.execute(s.toString());
          }

          @Override
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          @Override
          public void afterTextChanged(Editable s) {}
        });
    txtSearch.setOnKeyListener(
        new OnKeyListener() {
          @Override
          public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) return true;
            return false;
          }
        });
    switch (v.getId()) {
      case R.id.btn_manage:
        startActivityForResult(
            new Intent(RssReaderActivity.this, RssManageActivity.class), REQ_RSS_MANAGE);
        break;

      case R.id.btn_browse:
        rssProvider = dbQuery.getRssProviderList(null);
        int length = rssProvider.getProviderNames().length;
        if (length == 0) break;

        String[] providers = new String[length + 1];
        providers[0] = "All";
        for (int i = 0; i < length; i++) providers[i + 1] = rssProvider.getProviderNames()[i];
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder
            .setTitle(R.string.rss_choose_provider)
            .setItems(
                providers,
                new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int item) {
                    if (item == 0) {
                      loadData(null, true, false, false);
                      return;
                    }
                    loadData(rssProvider.getProviderNames()[item - 1], false, false, false);
                    curProvider = item - 1;
                    updateListView();
                  }
                });
        builder.create().show();
        break;

      case R.id.btn_refresh:
        if (curProvider == -1) loadData(null, true, true, true);
        else
          loadData(
              dbQuery.getRssProviderList(null).getProviderNames()[curProvider], false, true, true);
        break;

      case R.id.btn_search:
        if (txtSearchLabel.getText().toString().equals(getString(R.string.btn_search_text))) {
          btnManage.setVisibility(View.GONE);
          txtManageLabel.setVisibility(View.GONE);
          btnBrowse.setVisibility(View.GONE);
          txtBrowseLabel.setVisibility(View.GONE);
          btnRefresh.setVisibility(View.GONE);
          txtRefreshLabel.setVisibility(View.GONE);
          btnSearch.setBackgroundResource(R.drawable.btn_done_background);
          txtSearchLabel.setText(R.string.btn_done_text);
          txtSearch.setVisibility(View.VISIBLE);
          txtSearch.requestFocus();
        } else {
          btnManage.setVisibility(View.VISIBLE);
          txtManageLabel.setVisibility(View.VISIBLE);
          btnBrowse.setVisibility(View.VISIBLE);
          txtBrowseLabel.setVisibility(View.VISIBLE);
          btnRefresh.setVisibility(View.VISIBLE);
          txtRefreshLabel.setVisibility(View.VISIBLE);
          btnSearch.setBackgroundResource(R.drawable.btn_search_background);
          txtSearchLabel.setText(R.string.btn_search_text);
          txtSearch.setVisibility(View.GONE);
          txtSearch.setText("");
          loadData(null, true, false, false);
        }
        break;
      default:
        break;
    }
  }
示例#28
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    user = (EditText) findViewById(R.id.user);
    pass = (EditText) findViewById(R.id.pass);
    imgBtn = (ImageButton) findViewById(R.id.imgBtn);
    subLayout = (LinearLayout) this.findViewById(R.id.subLayout);
    mContext = this;
    btn = (Button) findViewById(R.id.btn);
    extensionBtn = (Button) findViewById(R.id.extensionBtn);

    // Generate textview dynamically
    TextView tv = new TextView(this);
    tv.setText("这是动态添加的textView");
    subLayout.addView(tv);

    View.OnClickListener imgBtnListener =
        new View.OnClickListener() {
          public void onClick(View view) {
            if (user.getText().toString().equals("LeiBusi")
                && pass.getText().toString().equals("Halo3Q")) {
              user.setVisibility(View.GONE);
              pass.setVisibility(View.GONE);
              imgBtn.setImageResource(R.mipmap.state2);
            } else {
              user.setText("LeiBusi");
              pass.setText("");
              pass.setHint("帐号或密码错误");
              pass.requestFocus();

              Toast toast = Toast.makeText(mContext, "密码错误", Toast.LENGTH_LONG);
              toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
              toast.show();
            }
          }
        };

    View.OnLongClickListener imgBtnLongListener =
        new View.OnLongClickListener() {
          public boolean onLongClick(View view) {
            TextView tv = new TextView(mContext);
            tv.setText("这是动态添加的textView");
            subLayout.addView(tv);
            return true;
          }
        };

    View.OnClickListener btnListener =
        new View.OnClickListener() {
          public void onClick(View view) {
            user.setText("");
            pass.setText("");
            pass.setHint("请输入密码");
            user.setVisibility(View.VISIBLE);
            pass.setVisibility(View.VISIBLE);
            user.requestFocus();
            imgBtn.setImageResource(R.mipmap.state1);

            if (subLayout.getChildCount() > 0) {
              subLayout.removeAllViews();
            }

            TextView tv = new TextView(mContext);
            tv.setText("这是动态添加的textView");
            subLayout.addView(tv);
          }
        };

    View.OnClickListener extensionBtnListener =
        new View.OnClickListener() {
          public void onClick(View view) {
            Intent Extra = new Intent(MainActivity.this, Extra.class);
            startActivity(Extra);
          }
        };

    imgBtn.setOnClickListener(imgBtnListener);
    imgBtn.setOnLongClickListener(imgBtnLongListener);
    btn.setOnClickListener(btnListener);
    extensionBtn.setOnClickListener(extensionBtnListener);
  }