List of usage examples for android.widget LinearLayout setOrientation
public void setOrientation(@OrientationMode int orientation)
From source file:foam.mongoose.StarwispBuilder.java
public void Build(final StarwispActivity ctx, final String ctxname, JSONArray arr, ViewGroup parent) { try {//from w w w . ja v a2 s . c o m String type = arr.getString(0); //Log.i("starwisp","building started "+type); if (type.equals("build-fragment")) { String name = arr.getString(1); int ID = arr.getInt(2); Fragment fragment = ActivityManager.GetFragment(name); LinearLayout inner = new LinearLayout(ctx); inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); inner.setId(ID); FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction(); fragmentTransaction.add(ID, fragment); fragmentTransaction.commit(); parent.addView(inner); return; } if (type.equals("linear-layout")) { LinearLayout v = new LinearLayout(ctx); v.setId(arr.getInt(1)); v.setOrientation(BuildOrientation(arr.getString(2))); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); //v.setPadding(2,2,2,2); JSONArray col = arr.getJSONArray(4); v.setBackgroundColor(Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2))); parent.addView(v); JSONArray children = arr.getJSONArray(5); for (int i = 0; i < children.length(); i++) { Build(ctx, ctxname, new JSONArray(children.getString(i)), v); } return; } if (type.equals("frame-layout")) { FrameLayout v = new FrameLayout(ctx); v.setId(arr.getInt(1)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); parent.addView(v); JSONArray children = arr.getJSONArray(3); for (int i = 0; i < children.length(); i++) { Build(ctx, ctxname, new JSONArray(children.getString(i)), v); } return; } /* if (type.equals("grid-layout")) { GridLayout v = new GridLayout(ctx); v.setId(arr.getInt(1)); v.setRowCount(arr.getInt(2)); //v.setColumnCount(arr.getInt(2)); v.setOrientation(BuildOrientation(arr.getString(3))); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4))); parent.addView(v); JSONArray children = arr.getJSONArray(5); for (int i=0; i<children.length(); i++) { Build(ctx,ctxname,new JSONArray(children.getString(i)), v); } return; } */ if (type.equals("scroll-view")) { HorizontalScrollView v = new HorizontalScrollView(ctx); v.setId(arr.getInt(1)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); parent.addView(v); JSONArray children = arr.getJSONArray(3); for (int i = 0; i < children.length(); i++) { Build(ctx, ctxname, new JSONArray(children.getString(i)), v); } return; } if (type.equals("scroll-view-vert")) { ScrollView v = new ScrollView(ctx); v.setId(arr.getInt(1)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); parent.addView(v); JSONArray children = arr.getJSONArray(3); for (int i = 0; i < children.length(); i++) { Build(ctx, ctxname, new JSONArray(children.getString(i)), v); } return; } if (type.equals("view-pager")) { ViewPager v = new ViewPager(ctx); v.setId(arr.getInt(1)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); v.setOffscreenPageLimit(3); final JSONArray items = arr.getJSONArray(3); v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) { @Override public int getCount() { return items.length(); } @Override public Fragment getItem(int position) { try { String fragname = items.getString(position); return ActivityManager.GetFragment(fragname); } catch (JSONException e) { Log.e("starwisp", "Error parsing data " + e.toString()); } return null; } }); parent.addView(v); return; } if (type.equals("space")) { // Space v = new Space(ctx); (class not found runtime error??) TextView v = new TextView(ctx); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); parent.addView(v); } if (type.equals("image-view")) { ImageView v = new ImageView(ctx); v.setId(arr.getInt(1)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); String image = arr.getString(2); if (image.startsWith("/")) { Bitmap bitmap = BitmapFactory.decodeFile(image); v.setImageBitmap(bitmap); } else { int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName()); v.setImageResource(id); } parent.addView(v); } if (type.equals("text-view")) { TextView v = new TextView(ctx); v.setId(arr.getInt(1)); v.setText(Html.fromHtml(arr.getString(2))); v.setTextSize(arr.getInt(3)); v.setMovementMethod(LinkMovementMethod.getInstance()); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4))); if (arr.length() > 5) { if (arr.getString(5).equals("left")) { v.setGravity(Gravity.LEFT); } else { if (arr.getString(5).equals("fill")) { v.setGravity(Gravity.FILL); } else { v.setGravity(Gravity.CENTER); } } } else { v.setGravity(Gravity.LEFT); } v.setTypeface(((StarwispActivity) ctx).m_Typeface); parent.addView(v); } if (type.equals("debug-text-view")) { TextView v = (TextView) ctx.getLayoutInflater().inflate(R.layout.debug_text, null); // v.setBackgroundResource(R.color.black); v.setId(arr.getInt(1)); // v.setText(Html.fromHtml(arr.getString(2))); // v.setTextColor(R.color.white); // v.setTextSize(arr.getInt(3)); // v.setMovementMethod(LinkMovementMethod.getInstance()); // v.setMaxLines(10); // v.setVerticalScrollBarEnabled(true); // v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4))); //v.setMovementMethod(new ScrollingMovementMethod()); /* if (arr.length()>5) { if (arr.getString(5).equals("left")) { v.setGravity(Gravity.LEFT); } else { if (arr.getString(5).equals("fill")) { v.setGravity(Gravity.FILL); } else { v.setGravity(Gravity.CENTER); } } } else { v.setGravity(Gravity.LEFT); } v.setTypeface(((StarwispActivity)ctx).m_Typeface);*/ parent.addView(v); } if (type.equals("web-view")) { WebView v = new WebView(ctx); v.setId(arr.getInt(1)); v.setVerticalScrollBarEnabled(false); v.loadData(arr.getString(2), "text/html", "utf-8"); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); parent.addView(v); } if (type.equals("edit-text")) { final EditText v = new EditText(ctx); v.setId(arr.getInt(1)); v.setText(arr.getString(2)); v.setTextSize(arr.getInt(3)); String inputtype = arr.getString(4); if (inputtype.equals("text")) { //v.setInputType(InputType.TYPE_CLASS_TEXT); } else if (inputtype.equals("numeric")) { v.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); } else if (inputtype.equals("email")) { v.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS); } v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(5))); v.setTypeface(((StarwispActivity) ctx).m_Typeface); final String fn = arr.getString(5); v.setSingleLine(true); v.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { CallbackArgs(ctx, ctxname, v.getId(), "\"" + s.toString() + "\""); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); parent.addView(v); } if (type.equals("button")) { Button v = new Button(ctx); v.setId(arr.getInt(1)); v.setText(arr.getString(2)); v.setTextSize(arr.getInt(3)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4))); v.setTypeface(((StarwispActivity) ctx).m_Typeface); final String fn = arr.getString(5); v.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Callback(ctx, ctxname, v.getId()); } }); parent.addView(v); } if (type.equals("toggle-button")) { ToggleButton v = new ToggleButton(ctx); if (arr.getString(5).equals("fancy")) { v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_fancy, null); } if (arr.getString(5).equals("yes")) { v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_yes, null); } if (arr.getString(5).equals("maybe")) { v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_maybe, null); } if (arr.getString(5).equals("no")) { v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_no, null); } v.setId(arr.getInt(1)); v.setText(arr.getString(2)); v.setTextSize(arr.getInt(3)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4))); v.setTypeface(((StarwispActivity) ctx).m_Typeface); final String fn = arr.getString(6); v.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String arg = "#f"; if (((ToggleButton) v).isChecked()) arg = "#t"; CallbackArgs(ctx, ctxname, v.getId(), arg); } }); parent.addView(v); } if (type.equals("seek-bar")) { SeekBar v = new SeekBar(ctx); v.setId(arr.getInt(1)); v.setMax(arr.getInt(2)); v.setProgress(arr.getInt(2) / 2); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); final String fn = arr.getString(4); v.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar v, int a, boolean s) { CallbackArgs(ctx, ctxname, v.getId(), Integer.toString(a)); } public void onStartTrackingTouch(SeekBar v) { } public void onStopTrackingTouch(SeekBar v) { } }); parent.addView(v); } if (type.equals("spinner")) { Spinner v = new Spinner(ctx); final int wid = arr.getInt(1); v.setId(wid); final JSONArray items = arr.getJSONArray(2); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); ArrayList<String> spinnerArray = new ArrayList<String>(); for (int i = 0; i < items.length(); i++) { spinnerArray.add(items.getString(i)); } ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item, spinnerArray) { public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface); return v; } }; spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout); v.setAdapter(spinnerArrayAdapter); v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> a, View v, int pos, long id) { try { CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\""); } catch (JSONException e) { Log.e("starwisp", "Error parsing data " + e.toString()); } } public void onNothingSelected(AdapterView<?> v) { } }); parent.addView(v); } if (type.equals("canvas")) { StarwispCanvas v = new StarwispCanvas(ctx); final int wid = arr.getInt(1); v.setId(wid); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); v.SetDrawList(arr.getJSONArray(3)); parent.addView(v); } if (type.equals("camera-preview")) { PictureTaker pt = new PictureTaker(); CameraPreview v = new CameraPreview(ctx, pt); final int wid = arr.getInt(1); v.setId(wid); // LinearLayout.LayoutParams lp = // new LinearLayout.LayoutParams(minWidth, minHeight, 1); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); // v.setLayoutParams(lp); parent.addView(v); } if (type.equals("button-grid")) { LinearLayout horiz = new LinearLayout(ctx); final int id = arr.getInt(1); final String buttontype = arr.getString(2); horiz.setId(id); horiz.setOrientation(LinearLayout.HORIZONTAL); parent.addView(horiz); int height = arr.getInt(3); int textsize = arr.getInt(4); LinearLayout.LayoutParams lp = BuildLayoutParams(arr.getJSONArray(5)); JSONArray buttons = arr.getJSONArray(6); int count = buttons.length(); int vertcount = 0; LinearLayout vert = null; for (int i = 0; i < count; i++) { JSONArray button = buttons.getJSONArray(i); if (vertcount == 0) { vert = new LinearLayout(ctx); vert.setId(0); vert.setOrientation(LinearLayout.VERTICAL); horiz.addView(vert); } vertcount = (vertcount + 1) % height; if (buttontype.equals("button")) { Button b = new Button(ctx); b.setId(button.getInt(0)); b.setText(button.getString(1)); b.setTextSize(textsize); b.setLayoutParams(lp); b.setTypeface(((StarwispActivity) ctx).m_Typeface); final String fn = arr.getString(6); b.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t"); } }); vert.addView(b); } else if (buttontype.equals("toggle")) { ToggleButton b = new ToggleButton(ctx); b.setId(button.getInt(0)); b.setText(button.getString(1)); b.setTextSize(textsize); b.setLayoutParams(lp); b.setTypeface(((StarwispActivity) ctx).m_Typeface); final String fn = arr.getString(6); b.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String arg = "#f"; if (((ToggleButton) v).isChecked()) arg = "#t"; CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg); } }); vert.addView(b); } } } } catch (JSONException e) { Log.e("starwisp", "Error parsing [" + arr.toString() + "] " + e.toString()); } //Log.i("starwisp","building ended"); }
From source file:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java
/** Called when the activity is first created. */ @Override/*from w ww.ja v a 2 s . c om*/ public void onCreate(Bundle savedInstanceState) { final Context context = this.getApplicationContext(); { ExceptionHandler.initialize(context); if (ExceptionHandler.needReport()) { final String fileName = ExceptionHandler.getBugReportFileAbsolutePath(); final File file = new File(fileName); final File fileZip; { String strFileZip = file.getAbsolutePath(); { int index = strFileZip.lastIndexOf('.'); if (0 < index) { strFileZip = strFileZip.substring(0, index); strFileZip += ".zip"; } } Log.d(TAG, strFileZip); fileZip = new File(strFileZip); if (fileZip.exists()) { fileZip.delete(); } } if (file.exists()) { Log.d(TAG, file.getAbsolutePath()); InputStream inStream = null; ZipOutputStream outStream = null; try { inStream = new FileInputStream(file); String strFileName = file.getAbsolutePath(); { int index = strFileName.lastIndexOf(File.separatorChar); if (0 < index) { strFileName = strFileName.substring(index + 1); } } Log.d(TAG, strFileName); outStream = new ZipOutputStream(new FileOutputStream(fileZip)); byte[] buff = new byte[8124]; { ZipEntry entry = new ZipEntry(strFileName); outStream.putNextEntry(entry); int len = 0; while (0 < (len = inStream.read(buff))) { outStream.write(buff, 0, len); } outStream.closeEntry(); } outStream.finish(); outStream.flush(); } catch (IOException e) { Log.e(TAG, "got exception", e); } finally { if (null != outStream) { try { outStream.close(); } catch (Exception e) { } } outStream = null; if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } inStream = null; } Log.i(TAG, "zip created"); } if (file.exists()) { // upload or send e-mail InputStream inStream = null; StringBuilder sb = new StringBuilder(); try { inStream = new FileInputStream(file); byte[] buff = new byte[8124]; int readed = 0; do { readed = inStream.read(buff); for (int i = 0; i < readed; i++) { sb.append((char) buff[i]); } } while (readed >= 0); final String str = sb.toString(); Log.i(TAG, str); } catch (IOException e) { Log.e(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } inStream = null; } AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if (null != defaultLocale) { if (defaultLocale.equals(Locale.JAPANESE) || defaultLocale.equals(Locale.JAPAN)) { title = ""; message = "?????????"; positive = "?"; negative = ""; needDefaultLang = false; } } if (needDefaultLang) { title = "ERROR"; message = "Got unexpected error. Do you want to send information of error."; positive = "Send"; negative = "Cancel"; } alertDialog.setTitle(title); alertDialog.setMessage(message); alertDialog.setPositiveButton(positive + " mail", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { DefaultUploaderMailClient.upload(context, file, new String[] { "diverKon+sakura@gmail.com" }); } }); alertDialog.setNeutralButton(positive + " http", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { DefaultUploaderWeb.upload(ExceptionHandlerReportApp.this, fileZip, "http://kkkon.sakura.ne.jp/android/bug"); } }); alertDialog.setNegativeButton(negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { ExceptionHandler.clearReport(); } }); alertDialog.show(); } // TODO separate activity for crash report //DefaultCheckerAPK.checkAPK( this, null ); } ExceptionHandler.registHandler(); } super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("ExceptionHandler"); layout.addView(tv); Button btn1 = new Button(this); btn1.setText("invoke Exception"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int count = 2; int[] array = new int[count]; int value = array[count]; // invoke IndexOutOfBOundsException } }); layout.addView(btn1); Button btn2 = new Button(this); btn2.setText("reinstall apk"); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean foundApk = false; { final String apkPath = context.getPackageCodePath(); // API8 Log.d(TAG, "PackageCodePath: " + apkPath); final File fileApk = new File(apkPath); if (fileApk.exists()) { foundApk = true; Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setDataAndType(Uri.fromFile(fileApk), "application/vnd.android.package-archive"); promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(promptInstall); } } if (false == foundApk) { for (int i = 0; i < 10; ++i) { File fileApk = new File("/data/app/" + context.getPackageName() + "-" + i + ".apk"); Log.d(TAG, "check apk:" + fileApk.getAbsolutePath()); if (fileApk.exists()) { Log.i(TAG, "apk found. path=" + fileApk.getAbsolutePath()); /* * // require parmission { final String strCmd = "pm install -r " + fileApk.getAbsolutePath(); try { Runtime.getRuntime().exec( strCmd ); } catch ( IOException e ) { Log.e( TAG, "got exception", e ); } } */ Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setDataAndType(Uri.fromFile(fileApk), "application/vnd.android.package-archive"); promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(promptInstall); break; } } } } }); layout.addView(btn2); Button btn3 = new Button(this); btn3.setText("check apk"); btn3.setOnClickListener(new View.OnClickListener() { private boolean checkApk(final File fileApk, final ZipEntryFilter filter) { final boolean[] result = new boolean[1]; result[0] = true; final Thread thread = new Thread(new Runnable() { @Override public void run() { if (fileApk.exists()) { ZipFile zipFile = null; try { zipFile = new ZipFile(fileApk); List<ZipEntry> list = new ArrayList<ZipEntry>(zipFile.size()); for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) { ZipEntry ent = e.nextElement(); Log.d(TAG, ent.getName()); Log.d(TAG, "" + ent.getSize()); final boolean accept = filter.accept(ent); if (accept) { list.add(ent); } } Log.d(TAG, Build.CPU_ABI); // API 4 Log.d(TAG, Build.CPU_ABI2); // API 8 final String[] abiArray = { Build.CPU_ABI // API 4 , Build.CPU_ABI2 // API 8 }; String abiMatched = null; { boolean foundMatched = false; for (final String abi : abiArray) { if (null == abi) { continue; } if (0 == abi.length()) { continue; } for (final ZipEntry entry : list) { Log.d(TAG, entry.getName()); final String prefixABI = "lib/" + abi + "/"; if (entry.getName().startsWith(prefixABI)) { abiMatched = abi; foundMatched = true; break; } } if (foundMatched) { break; } } } Log.d(TAG, "matchedAbi=" + abiMatched); if (null != abiMatched) { boolean needReInstall = false; for (final ZipEntry entry : list) { Log.d(TAG, entry.getName()); final String prefixABI = "lib/" + abiMatched + "/"; if (entry.getName().startsWith(prefixABI)) { final String jniName = entry.getName().substring(prefixABI.length()); Log.d(TAG, "jni=" + jniName); final String strFileDst = context.getApplicationInfo().nativeLibraryDir + "/" + jniName; Log.d(TAG, strFileDst); final File fileDst = new File(strFileDst); if (!fileDst.exists()) { Log.w(TAG, "needReInstall: content missing " + strFileDst); needReInstall = true; } else { assert (entry.getSize() <= Integer.MAX_VALUE); if (fileDst.length() != entry.getSize()) { Log.w(TAG, "needReInstall: size broken " + strFileDst); needReInstall = true; } else { //org.apache.commons.io.IOUtils.contentEquals( zipFile.getInputStream( entry ), new FileInputStream(fileDst) ); final int size = (int) entry.getSize(); byte[] buffSrc = new byte[size]; { InputStream inStream = null; try { inStream = zipFile.getInputStream(entry); int pos = 0; { while (pos < size) { final int ret = inStream.read(buffSrc, pos, size - pos); if (ret <= 0) { break; } pos += ret; } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } } } byte[] buffDst = new byte[(int) fileDst.length()]; { InputStream inStream = null; try { inStream = new FileInputStream(fileDst); int pos = 0; { while (pos < size) { final int ret = inStream.read(buffDst, pos, size - pos); if (ret <= 0) { break; } pos += ret; } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } } } if (Arrays.equals(buffSrc, buffDst)) { Log.d(TAG, " content equal " + strFileDst); // OK } else { Log.w(TAG, "needReInstall: content broken " + strFileDst); needReInstall = true; } } } } } // for ZipEntry if (needReInstall) { // need call INSTALL APK Log.w(TAG, "needReInstall apk"); result[0] = false; } else { Log.d(TAG, "no need ReInstall apk"); } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != zipFile) { try { zipFile.close(); } catch (Exception e) { } } } } } }); thread.setName("check jni so"); thread.start(); /* while ( thread.isAlive() ) { Log.d( TAG, "check thread.id=" + android.os.Process.myTid() + ",state=" + thread.getState() ); if ( ! thread.isAlive() ) { break; } AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this ); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if ( null != defaultLocale ) { if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) ) { title = ""; message = "???????"; positive = "?"; negative = ""; needDefaultLang = false; } } if ( needDefaultLang ) { title = "INFO"; message = "Now checking installation. Cancel check?"; positive = "Wait"; negative = "Cancel"; } alertDialog.setTitle( title ); alertDialog.setMessage( message ); alertDialog.setPositiveButton( positive, null); alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { if ( thread.isAlive() ) { Log.d( TAG, "request interrupt" ); thread.interrupt(); } else { // nothing } } } ); if ( ! thread.isAlive() ) { break; } alertDialog.show(); if ( ! Thread.State.RUNNABLE.equals(thread.getState()) ) { break; } } */ try { thread.join(); } catch (InterruptedException e) { Log.d(TAG, "got exception", e); } return result[0]; } @Override public void onClick(View view) { boolean foundApk = false; { final String apkPath = context.getPackageCodePath(); // API8 Log.d(TAG, "PackageCodePath: " + apkPath); final File fileApk = new File(apkPath); this.checkApk(fileApk, new ZipEntryFilter() { @Override public boolean accept(ZipEntry entry) { if (entry.isDirectory()) { return false; } final String filename = entry.getName(); if (filename.startsWith("lib/")) { return true; } return false; } }); } } }); layout.addView(btn3); Button btn4 = new Button(this); btn4.setText("print dir and path"); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { { final File file = context.getCacheDir(); Log.d(TAG, "Ctx.CacheDir=" + file.getAbsoluteFile()); } { final File file = context.getExternalCacheDir(); // API 8 if (null == file) { // no permission Log.d(TAG, "Ctx.ExternalCacheDir="); } else { Log.d(TAG, "Ctx.ExternalCacheDir=" + file.getAbsolutePath()); } } { final File file = context.getFilesDir(); Log.d(TAG, "Ctx.FilesDir=" + file.getAbsolutePath()); } { final String value = context.getPackageResourcePath(); Log.d(TAG, "Ctx.PackageResourcePath=" + value); } { final String[] files = context.fileList(); if (null == files) { Log.d(TAG, "Ctx.fileList=" + files); } else { for (final String filename : files) { Log.d(TAG, "Ctx.fileList=" + filename); } } } { final File file = Environment.getDataDirectory(); Log.d(TAG, "Env.DataDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getDownloadCacheDirectory(); Log.d(TAG, "Env.DownloadCacheDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getExternalStorageDirectory(); Log.d(TAG, "Env.ExternalStorageDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getRootDirectory(); Log.d(TAG, "Env.RootDirectory=" + file.getAbsolutePath()); } { final ApplicationInfo appInfo = context.getApplicationInfo(); Log.d(TAG, "AppInfo.dataDir=" + appInfo.dataDir); Log.d(TAG, "AppInfo.nativeLibraryDir=" + appInfo.nativeLibraryDir); // API 9 Log.d(TAG, "AppInfo.publicSourceDir=" + appInfo.publicSourceDir); { final String[] sharedLibraryFiles = appInfo.sharedLibraryFiles; if (null == sharedLibraryFiles) { Log.d(TAG, "AppInfo.sharedLibraryFiles=" + sharedLibraryFiles); } else { for (final String fileName : sharedLibraryFiles) { Log.d(TAG, "AppInfo.sharedLibraryFiles=" + fileName); } } } Log.d(TAG, "AppInfo.sourceDir=" + appInfo.sourceDir); } { Log.d(TAG, "System.Properties start"); final Properties properties = System.getProperties(); if (null != properties) { for (final Object key : properties.keySet()) { String value = properties.getProperty((String) key); Log.d(TAG, " key=" + key + ",value=" + value); } } Log.d(TAG, "System.Properties end"); } { Log.d(TAG, "System.getenv start"); final Map<String, String> mapEnv = System.getenv(); if (null != mapEnv) { for (final Map.Entry<String, String> entry : mapEnv.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); Log.d(TAG, " key=" + key + ",value=" + value); } } Log.d(TAG, "System.getenv end"); } } }); layout.addView(btn4); Button btn5 = new Button(this); btn5.setText("check INSTALL_NON_MARKET_APPS"); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SettingsCompat.initialize(context); if (SettingsCompat.isAllowedNonMarketApps()) { Log.d(TAG, "isAllowdNonMarketApps=true"); } else { Log.d(TAG, "isAllowdNonMarketApps=false"); } } }); layout.addView(btn5); Button btn6 = new Button(this); btn6.setText("send email"); btn6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent mailto = new Intent(); mailto.setAction(Intent.ACTION_SENDTO); mailto.setType("message/rfc822"); mailto.setData(Uri.parse("mailto:")); mailto.putExtra(Intent.EXTRA_EMAIL, new String[] { "" }); mailto.putExtra(Intent.EXTRA_SUBJECT, "[BugReport] " + context.getPackageName()); mailto.putExtra(Intent.EXTRA_TEXT, "body text"); //mailto.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); //context.startActivity( mailto ); Intent intent = Intent.createChooser(mailto, "Send Email"); if (null != intent) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { Log.d(TAG, "got Exception", e); } } } }); layout.addView(btn6); Button btn7 = new Button(this); btn7.setText("upload http thread"); btn7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG, "brd=" + Build.BRAND); Log.d(TAG, "prd=" + Build.PRODUCT); //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); final Thread thread = new Thread(new Runnable() { @Override public void run() { Log.d(TAG, "upload thread tid=" + android.os.Process.myTid()); try { HttpPost httpPost = new HttpPost("http://kkkon.sakura.ne.jp/android/bug"); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); } Log.d(TAG, "upload finish"); } }); thread.setName("upload crash"); thread.start(); /* while ( thread.isAlive() ) { Log.d( TAG, "thread tid=" + android.os.Process.myTid() + ",state=" + thread.getState() ); if ( ! thread.isAlive() ) { break; } AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this ); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if ( null != defaultLocale ) { if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) ) { title = ""; message = "???????"; positive = "?"; negative = ""; needDefaultLang = false; } } if ( needDefaultLang ) { title = "INFO"; message = "Now uploading error information. Cancel upload?"; positive = "Wait"; negative = "Cancel"; } alertDialog.setTitle( title ); alertDialog.setMessage( message ); alertDialog.setPositiveButton( positive, null); alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { if ( thread.isAlive() ) { Log.d( TAG, "request interrupt" ); thread.interrupt(); } else { // nothing } } } ); if ( ! thread.isAlive() ) { break; } alertDialog.show(); if ( ! Thread.State.RUNNABLE.equals(thread.getState()) ) { break; } } */ /* try { thread.join(); // must call. leak handle... } catch ( InterruptedException e ) { Log.d( TAG, "got Exception", e ); } */ } }); layout.addView(btn7); Button btn8 = new Button(this); btn8.setText("upload http AsyncTask"); btn8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... paramss) { Boolean result = true; Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid()); try { //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); HttpPost httpPost = new HttpPost(paramss[0]); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); result = false; } Log.d(TAG, "upload finish"); return result; } }; asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug"); asyncTask.isCancelled(); } }); layout.addView(btn8); Button btn9 = new Button(this); btn9.setText("call checkAPK"); btn9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final boolean result = DefaultCheckerAPK.checkAPK(ExceptionHandlerReportApp.this, null); Log.i(TAG, "checkAPK result=" + result); } }); layout.addView(btn9); setContentView(layout); }
From source file:com.keylesspalace.tusky.ComposeActivity.java
private void makeCaptionDialog(QueuedMedia item) { LinearLayout dialogLayout = new LinearLayout(this); int padding = Utils.dpToPx(this, 8); dialogLayout.setPadding(padding, padding, padding, padding); dialogLayout.setOrientation(LinearLayout.VERTICAL); ImageView imageView = new ImageView(this); DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); Picasso.with(this).load(item.uri).resize(displayMetrics.widthPixels, displayMetrics.heightPixels) .onlyScaleDown().into(imageView); int margin = Utils.dpToPx(this, 4); dialogLayout.addView(imageView);//from w ww . j a va 2 s.c o m ((LinearLayout.LayoutParams) imageView.getLayoutParams()).weight = 1; imageView.getLayoutParams().height = 0; ((LinearLayout.LayoutParams) imageView.getLayoutParams()).setMargins(0, margin, 0, 0); EditText input = new EditText(this); input.setHint(R.string.hint_describe_for_visually_impaired); dialogLayout.addView(input); ((LinearLayout.LayoutParams) input.getLayoutParams()).setMargins(margin, margin, margin, margin); input.setLines(1); input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); input.setText(item.description); DialogInterface.OnClickListener okListener = (dialog, which) -> { mastodonApi.updateMedia(item.id, input.getText().toString()).enqueue(new Callback<Attachment>() { @Override public void onResponse(@NonNull Call<Attachment> call, @NonNull Response<Attachment> response) { Attachment attachment = response.body(); if (response.isSuccessful() && attachment != null) { item.description = attachment.getDescription(); item.preview.setChecked(item.description != null && !item.description.isEmpty()); dialog.dismiss(); } else { showFailedCaptionMessage(); } } @Override public void onFailure(@NonNull Call<Attachment> call, @NonNull Throwable t) { showFailedCaptionMessage(); } }); }; AlertDialog dialog = new AlertDialog.Builder(this).setView(dialogLayout) .setPositiveButton(android.R.string.ok, okListener).setNegativeButton(android.R.string.cancel, null) .create(); Window window = dialog.getWindow(); if (window != null) { window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); } dialog.show(); }
From source file:org.telegram.ui.SettingsActivity.java
@Override public View createView(Context context) { actionBar.setBackgroundColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue)); actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_avatar_actionBarSelectorBlue), false); actionBar.setItemsColor(Theme.getColor(Theme.key_avatar_actionBarIconBlue), false); actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAddToContainer(false);/*from w ww.j av a2s. co m*/ extraHeight = 88; if (AndroidUtilities.isTablet()) { actionBar.setOccupyStatusBar(false); } actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == edit_name) { presentFragment(new ChangeNameActivity()); } else if (id == logout) { presentFragment(new LogoutActivity()); } } }); ActionBarMenu menu = actionBar.createMenu(); ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName)); item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut)); int scrollTo; int scrollToPosition = 0; Object writeButtonTag = null; if (listView != null) { scrollTo = layoutManager.findFirstVisibleItemPosition(); View topView = layoutManager.findViewByPosition(scrollTo); if (topView != null) { scrollToPosition = topView.getTop(); } else { scrollTo = -1; } writeButtonTag = writeButton.getTag(); } else { scrollTo = -1; } listAdapter = new ListAdapter(context); fragmentView = new FrameLayout(context) { @Override protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) { if (child == listView) { boolean result = super.drawChild(canvas, child, drawingTime); if (parentLayout != null) { int actionBarHeight = 0; int childCount = getChildCount(); for (int a = 0; a < childCount; a++) { View view = getChildAt(a); if (view == child) { continue; } if (view instanceof ActionBar && view.getVisibility() == VISIBLE) { if (((ActionBar) view).getCastShadows()) { actionBarHeight = view.getMeasuredHeight(); } break; } } parentLayout.drawHeaderShadow(canvas, actionBarHeight); } return result; } else { return super.drawChild(canvas, child, drawingTime); } } }; fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray)); FrameLayout frameLayout = (FrameLayout) fragmentView; listView = new RecyclerListView(context); listView.setVerticalScrollBarEnabled(false); listView.setLayoutManager( layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) { @Override public boolean supportsPredictiveItemAnimations() { return false; } }); listView.setGlowColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue)); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); listView.setAdapter(listAdapter); listView.setItemAnimator(null); listView.setLayoutAnimation(null); listView.setOnItemClickListener((view, position) -> { if (position == notificationRow) { presentFragment(new NotificationsSettingsActivity()); } else if (position == privacyRow) { presentFragment(new PrivacySettingsActivity()); } else if (position == dataRow) { presentFragment(new DataSettingsActivity()); } else if (position == chatRow) { presentFragment(new ThemeActivity(ThemeActivity.THEME_TYPE_BASIC)); } else if (position == helpRow) { BottomSheet.Builder builder = new BottomSheet.Builder(context); builder.setApplyTopPadding(false); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); HeaderCell headerCell = new HeaderCell(context, true, 23, 15, false); headerCell.setHeight(47); headerCell.setText(LocaleController.getString("SettingsHelp", R.string.SettingsHelp)); linearLayout.addView(headerCell); LinearLayout linearLayoutInviteContainer = new LinearLayout(context); linearLayoutInviteContainer.setOrientation(LinearLayout.VERTICAL); linearLayout.addView(linearLayoutInviteContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); int count = 6; for (int a = 0; a < count; a++) { if (a >= 3 && a <= 4 && !BuildVars.LOGS_ENABLED || a == 5 && !BuildVars.DEBUG_VERSION) { continue; } TextCell textCell = new TextCell(context); String text; switch (a) { case 0: text = LocaleController.getString("AskAQuestion", R.string.AskAQuestion); break; case 1: text = LocaleController.getString("TelegramFAQ", R.string.TelegramFAQ); break; case 2: text = LocaleController.getString("PrivacyPolicy", R.string.PrivacyPolicy); break; case 3: text = LocaleController.getString("DebugSendLogs", R.string.DebugSendLogs); break; case 4: text = LocaleController.getString("DebugClearLogs", R.string.DebugClearLogs); break; case 5: default: text = "Switch Backend"; break; } textCell.setText(text, BuildVars.LOGS_ENABLED || BuildVars.DEBUG_VERSION ? a != count - 1 : a != 2); textCell.setTag(a); textCell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); linearLayoutInviteContainer.addView(textCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); textCell.setOnClickListener(v2 -> { Integer tag = (Integer) v2.getTag(); switch (tag) { case 0: { showDialog(AlertsCreator.createSupportAlert(SettingsActivity.this)); break; } case 1: Browser.openUrl(getParentActivity(), LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl)); break; case 2: Browser.openUrl(getParentActivity(), LocaleController.getString("PrivacyPolicyUrl", R.string.PrivacyPolicyUrl)); break; case 3: sendLogs(); break; case 4: FileLog.cleanupLogs(); break; case 5: { if (getParentActivity() == null) { return; } AlertDialog.Builder builder1 = new AlertDialog.Builder(getParentActivity()); builder1.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); builder1.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder1.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> { SharedConfig.pushAuthKey = null; SharedConfig.pushAuthKeyId = null; SharedConfig.saveConfig(); ConnectionsManager.getInstance(currentAccount).switchBackend(); }); builder1.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder1.create()); break; } } builder.getDismissRunnable().run(); }); } builder.setCustomView(linearLayout); showDialog(builder.create()); } else if (position == languageRow) { presentFragment(new LanguageSelectActivity()); } else if (position == usernameRow) { presentFragment(new ChangeUsernameActivity()); } else if (position == bioRow) { if (userInfo != null) { presentFragment(new ChangeBioActivity()); } } else if (position == numberRow) { presentFragment(new ChangePhoneHelpActivity()); } }); listView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() { private int pressCount = 0; @Override public boolean onItemClick(View view, int position) { if (position == versionRow) { pressCount++; if (pressCount >= 2 || BuildVars.DEBUG_PRIVATE_VERSION) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("DebugMenu", R.string.DebugMenu)); CharSequence[] items; items = new CharSequence[] { LocaleController.getString("DebugMenuImportContacts", R.string.DebugMenuImportContacts), LocaleController.getString("DebugMenuReloadContacts", R.string.DebugMenuReloadContacts), LocaleController.getString("DebugMenuResetContacts", R.string.DebugMenuResetContacts), LocaleController.getString("DebugMenuResetDialogs", R.string.DebugMenuResetDialogs), BuildVars.LOGS_ENABLED ? LocaleController.getString("DebugMenuDisableLogs", R.string.DebugMenuDisableLogs) : LocaleController.getString("DebugMenuEnableLogs", R.string.DebugMenuEnableLogs), SharedConfig.inappCamera ? LocaleController.getString("DebugMenuDisableCamera", R.string.DebugMenuDisableCamera) : LocaleController.getString("DebugMenuEnableCamera", R.string.DebugMenuEnableCamera), LocaleController.getString("DebugMenuClearMediaCache", R.string.DebugMenuClearMediaCache), LocaleController.getString("DebugMenuCallSettings", R.string.DebugMenuCallSettings), null, BuildVars.DEBUG_PRIVATE_VERSION ? "Check for app updates" : null }; builder.setItems(items, (dialog, which) -> { if (which == 0) { UserConfig.getInstance(currentAccount).syncContacts = true; UserConfig.getInstance(currentAccount).saveConfig(false); ContactsController.getInstance(currentAccount).forceImportContacts(); } else if (which == 1) { ContactsController.getInstance(currentAccount).loadContacts(false, 0); } else if (which == 2) { ContactsController.getInstance(currentAccount).resetImportedContacts(); } else if (which == 3) { MessagesController.getInstance(currentAccount).forceResetDialogs(); } else if (which == 4) { BuildVars.LOGS_ENABLED = !BuildVars.LOGS_ENABLED; SharedPreferences sharedPreferences = ApplicationLoader.applicationContext .getSharedPreferences("systemConfig", Context.MODE_PRIVATE); sharedPreferences.edit().putBoolean("logsEnabled", BuildVars.LOGS_ENABLED).commit(); } else if (which == 5) { SharedConfig.toggleInappCamera(); } else if (which == 6) { MessagesStorage.getInstance(currentAccount).clearSentMedia(); SharedPreferences.Editor editor = MessagesController.getGlobalMainSettings().edit(); SharedConfig.setNoSoundHintShowed(false); } else if (which == 7) { VoIPHelper.showCallDebugSettings(getParentActivity()); } else if (which == 8) { SharedConfig.toggleRoundCamera16to9(); } else if (which == 9) { ((LaunchActivity) getParentActivity()).checkAppUpdate(true); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else { try { Toast.makeText(getParentActivity(), "\\_()_/", Toast.LENGTH_SHORT).show(); } catch (Exception e) { FileLog.e(e); } } return true; } return false; } }); frameLayout.addView(actionBar); extraHeightView = new View(context); extraHeightView.setPivotY(0); extraHeightView.setBackgroundColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue)); frameLayout.addView(extraHeightView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 88)); shadowView = new View(context); shadowView.setBackgroundResource(R.drawable.header_shadow); frameLayout.addView(shadowView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3)); avatarContainer = new FrameLayout(context); avatarContainer.setPivotX(LocaleController.isRTL ? AndroidUtilities.dp(42) : 0); avatarContainer.setPivotY(0); frameLayout.addView(avatarContainer, LayoutHelper.createFrame(42, 42, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), (LocaleController.isRTL ? 0 : 64), 0, (LocaleController.isRTL ? 64 : 0), 0)); avatarContainer.setOnClickListener(v -> { if (avatar != null) { return; } TLRPC.User user = MessagesController.getInstance(currentAccount) .getUser(UserConfig.getInstance(currentAccount).getClientUserId()); if (user != null && user.photo != null && user.photo.photo_big != null) { PhotoViewer.getInstance().setParentActivity(getParentActivity()); PhotoViewer.getInstance().openPhoto(user.photo.photo_big, provider); } }); avatarImage = new BackupImageView(context); avatarImage.setRoundRadius(AndroidUtilities.dp(21)); avatarContainer.addView(avatarImage, LayoutHelper.createFrame(42, 42)); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(0x55000000); avatarProgressView = new RadialProgressView(context) { @Override protected void onDraw(Canvas canvas) { if (avatarImage != null && avatarImage.getImageReceiver().hasNotThumb()) { paint.setAlpha((int) (0x55 * avatarImage.getImageReceiver().getCurrentAlpha())); canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, AndroidUtilities.dp(21), paint); } super.onDraw(canvas); } }; avatarProgressView.setSize(AndroidUtilities.dp(26)); avatarProgressView.setProgressColor(0xffffffff); avatarContainer.addView(avatarProgressView, LayoutHelper.createFrame(42, 42)); showAvatarProgress(false, false); nameTextView = new TextView(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setPivotX(LocaleController.isRTL ? getMeasuredWidth() : 0); } }; nameTextView.setTextColor(Theme.getColor(Theme.key_profile_title)); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); nameTextView.setLines(1); nameTextView.setMaxLines(1); nameTextView.setSingleLine(true); nameTextView.setEllipsize(TextUtils.TruncateAt.END); nameTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView.setPivotY(0); frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 48 : 118, 0, LocaleController.isRTL ? 118 : 48, 0)); onlineTextView = new TextView(context); onlineTextView.setTextColor(Theme.getColor(Theme.key_avatar_subtitleInProfileBlue)); onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); onlineTextView.setLines(1); onlineTextView.setMaxLines(1); onlineTextView.setSingleLine(true); onlineTextView.setEllipsize(TextUtils.TruncateAt.END); onlineTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); frameLayout.addView(onlineTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 48 : 118, 0, LocaleController.isRTL ? 118 : 48, 0)); writeButton = new ImageView(context); Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_profile_actionBackground), Theme.getColor(Theme.key_profile_actionPressedBackground)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile) .mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0); combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56)); drawable = combinedDrawable; } writeButton.setBackgroundDrawable(drawable); writeButton.setImageResource(R.drawable.menu_camera_av); writeButton.setColorFilter( new PorterDuffColorFilter(Theme.getColor(Theme.key_profile_actionIcon), PorterDuff.Mode.MULTIPLY)); writeButton.setScaleType(ImageView.ScaleType.CENTER); if (Build.VERSION.SDK_INT >= 21) { StateListAnimator animator = new StateListAnimator(); animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator .ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)) .setDuration(200)); animator.addState(new int[] {}, ObjectAnimator .ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)) .setDuration(200)); writeButton.setStateListAnimator(animator); writeButton.setOutlineProvider(new ViewOutlineProvider() { @SuppressLint("NewApi") @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56)); } }); } frameLayout.addView(writeButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60, Build.VERSION.SDK_INT >= 21 ? 56 : 60, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP, LocaleController.isRTL ? 16 : 0, 0, LocaleController.isRTL ? 0 : 16, 0)); writeButton.setOnClickListener(v -> { TLRPC.User user = MessagesController.getInstance(currentAccount) .getUser(UserConfig.getInstance(currentAccount).getClientUserId()); if (user == null) { user = UserConfig.getInstance(currentAccount).getCurrentUser(); } if (user == null) { return; } imageUpdater.openMenu( user.photo != null && user.photo.photo_big != null && !(user.photo instanceof TLRPC.TL_userProfilePhotoEmpty), () -> MessagesController.getInstance(currentAccount).deleteUserPhoto(null)); }); if (scrollTo != -1) { layoutManager.scrollToPositionWithOffset(scrollTo, scrollToPosition); if (writeButtonTag != null) { writeButton.setTag(0); writeButton.setScaleX(0.2f); writeButton.setScaleY(0.2f); writeButton.setAlpha(0.0f); writeButton.setVisibility(View.GONE); } } needLayout(); listView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (layoutManager.getItemCount() == 0) { return; } int height = 0; View child = recyclerView.getChildAt(0); if (child != null) { if (layoutManager.findFirstVisibleItemPosition() == 0) { height = AndroidUtilities.dp(88) + (child.getTop() < 0 ? child.getTop() : 0); } if (extraHeight != height) { extraHeight = height; needLayout(); } } } }); return fragmentView; }
From source file:com.hippo.ehviewer.ui.scene.GalleryDetailScene.java
@SuppressWarnings("deprecation") private void bindTags(GalleryTagGroup[] tagGroups) { Context context = getContext2(); LayoutInflater inflater = getLayoutInflater2(); Resources resources = getResources2(); if (null == context || null == inflater || null == resources || null == mTags || null == mNoTags) { return;//from w ww . j a v a 2s . c om } mTags.removeViews(1, mTags.getChildCount() - 1); if (tagGroups == null || tagGroups.length == 0) { mNoTags.setVisibility(View.VISIBLE); return; } else { mNoTags.setVisibility(View.GONE); } int colorTag = resources.getColor(R.color.colorPrimary); int colorName = resources.getColor(R.color.purple_a400); for (GalleryTagGroup tg : tagGroups) { LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.gallery_tag_group, mTags, false); ll.setOrientation(LinearLayout.HORIZONTAL); mTags.addView(ll); TextView tgName = (TextView) inflater.inflate(R.layout.item_gallery_tag, ll, false); ll.addView(tgName); tgName.setText(tg.groupName); tgName.setBackgroundDrawable(new RoundSideRectDrawable(colorName)); AutoWrapLayout awl = new AutoWrapLayout(context); ll.addView(awl, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); for (int j = 0, z = tg.size(); j < z; j++) { TextView tag = (TextView) inflater.inflate(R.layout.item_gallery_tag, awl, false); awl.addView(tag); String tagStr = tg.getTagAt(j); tag.setText(tagStr); tag.setBackgroundDrawable(new RoundSideRectDrawable(colorTag)); tag.setTag(R.id.tag, tg.groupName + ":" + tagStr); tag.setOnClickListener(this); tag.setOnLongClickListener(this); } } }
From source file:org.telegram.ui.ThemeActivity.java
@Override public View createView(Context context) { actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(false); if (AndroidUtilities.isTablet()) { actionBar.setOccupyStatusBar(false); }//from www. j ava 2 s .co m if (currentType == THEME_TYPE_BASIC) { actionBar.setTitle(LocaleController.getString("ChatSettings", R.string.ChatSettings)); ActionBarMenu menu = actionBar.createMenu(); ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); item.addSubItem(create_theme, LocaleController.getString("CreateNewThemeMenu", R.string.CreateNewThemeMenu)); } else { actionBar.setTitle(LocaleController.getString("AutoNightTheme", R.string.AutoNightTheme)); } actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == create_theme) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("NewTheme", R.string.NewTheme)); builder.setMessage( LocaleController.getString("CreateNewThemeAlert", R.string.CreateNewThemeAlert)); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setPositiveButton(LocaleController.getString("CreateTheme", R.string.CreateTheme), (dialog, which) -> openThemeCreate()); showDialog(builder.create()); } } }); listAdapter = new ListAdapter(context); FrameLayout frameLayout = new FrameLayout(context); frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray)); fragmentView = frameLayout; listView = new RecyclerListView(context); listView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); listView.setVerticalScrollBarEnabled(false); listView.setAdapter(listAdapter); ((DefaultItemAnimator) listView.getItemAnimator()).setDelayAnimations(false); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); listView.setOnItemClickListener((view, position) -> { if (position == enableAnimationsRow) { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); boolean animations = preferences.getBoolean("view_animations", true); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("view_animations", !animations); editor.commit(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!animations); } } else if (position == backgroundRow) { presentFragment(new WallpapersListActivity(WallpapersListActivity.TYPE_ALL)); } else if (position == sendByEnterRow) { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); boolean send = preferences.getBoolean("send_by_enter", false); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("send_by_enter", !send); editor.commit(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (position == raiseToSpeakRow) { SharedConfig.toogleRaiseToSpeak(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(SharedConfig.raiseToSpeak); } } else if (position == saveToGalleryRow) { SharedConfig.toggleSaveToGallery(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(SharedConfig.saveToGallery); } } else if (position == customTabsRow) { SharedConfig.toggleCustomTabs(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(SharedConfig.customTabs); } } else if (position == directShareRow) { SharedConfig.toggleDirectShare(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(SharedConfig.directShare); } } else if (position == contactsReimportRow) { //not implemented } else if (position == contactsSortRow) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("SortBy", R.string.SortBy)); builder.setItems( new CharSequence[] { LocaleController.getString("Default", R.string.Default), LocaleController.getString("SortFirstName", R.string.SortFirstName), LocaleController.getString("SortLastName", R.string.SortLastName) }, (dialog, which) -> { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("sortContactsBy", which); editor.commit(); if (listAdapter != null) { listAdapter.notifyItemChanged(position); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else if (position == stickersRow) { presentFragment(new StickersActivity(DataQuery.TYPE_IMAGE)); } else if (position == emojiRow) { if (getParentActivity() == null) { return; } final boolean maskValues[] = new boolean[2]; BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity()); builder.setApplyTopPadding(false); builder.setApplyBottomPadding(false); LinearLayout linearLayout = new LinearLayout(getParentActivity()); linearLayout.setOrientation(LinearLayout.VERTICAL); for (int a = 0; a < (Build.VERSION.SDK_INT >= 19 ? 2 : 1); a++) { String name = null; if (a == 0) { maskValues[a] = SharedConfig.allowBigEmoji; name = LocaleController.getString("EmojiBigSize", R.string.EmojiBigSize); } else if (a == 1) { maskValues[a] = SharedConfig.useSystemEmoji; name = LocaleController.getString("EmojiUseDefault", R.string.EmojiUseDefault); } CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity(), 1, 21); checkBoxCell.setTag(a); checkBoxCell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); linearLayout.addView(checkBoxCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50)); checkBoxCell.setText(name, "", maskValues[a], true); checkBoxCell.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); checkBoxCell.setOnClickListener(v -> { CheckBoxCell cell = (CheckBoxCell) v; int num = (Integer) cell.getTag(); maskValues[num] = !maskValues[num]; cell.setChecked(maskValues[num], true); }); } BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1); cell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); cell.setTextAndIcon(LocaleController.getString("Save", R.string.Save).toUpperCase(), 0); cell.setTextColor(Theme.getColor(Theme.key_dialogTextBlue2)); cell.setOnClickListener(v -> { try { if (visibleDialog != null) { visibleDialog.dismiss(); } } catch (Exception e) { FileLog.e(e); } SharedPreferences.Editor editor = MessagesController.getGlobalMainSettings().edit(); editor.putBoolean("allowBigEmoji", SharedConfig.allowBigEmoji = maskValues[0]); editor.putBoolean("useSystemEmoji", SharedConfig.useSystemEmoji = maskValues[1]); editor.commit(); if (listAdapter != null) { listAdapter.notifyItemChanged(position); } }); linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50)); builder.setCustomView(linearLayout); showDialog(builder.create()); } else if (position >= themeStartRow && position < themeEndRow) { int p = position - themeStartRow; if (p >= 0 && p < Theme.themes.size()) { Theme.ThemeInfo themeInfo = Theme.themes.get(p); if (currentType == THEME_TYPE_BASIC) { if (themeInfo == Theme.getCurrentTheme()) { return; } NotificationCenter.getGlobalInstance() .postNotificationName(NotificationCenter.needSetDayNightTheme, themeInfo, false); } else { Theme.setCurrentNightTheme(themeInfo); } int count = listView.getChildCount(); for (int a = 0; a < count; a++) { View child = listView.getChildAt(a); if (child instanceof ThemeCell) { ((ThemeCell) child).updateCurrentThemeCheck(); } } } } else if (position == nightThemeRow) { presentFragment(new ThemeActivity(THEME_TYPE_NIGHT)); } else if (position == nightDisabledRow) { Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_NONE; updateRows(); Theme.checkAutoNightThemeConditions(); } else if (position == nightScheduledRow) { Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_SCHEDULED; if (Theme.autoNightScheduleByLocation) { updateSunTime(null, true); } updateRows(); Theme.checkAutoNightThemeConditions(); } else if (position == nightAutomaticRow) { Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_AUTOMATIC; updateRows(); Theme.checkAutoNightThemeConditions(); } else if (position == scheduleLocationRow) { Theme.autoNightScheduleByLocation = !Theme.autoNightScheduleByLocation; TextCheckCell checkCell = (TextCheckCell) view; checkCell.setChecked(Theme.autoNightScheduleByLocation); updateRows(); if (Theme.autoNightScheduleByLocation) { updateSunTime(null, true); } Theme.checkAutoNightThemeConditions(); } else if (position == scheduleFromRow || position == scheduleToRow) { if (getParentActivity() == null) { return; } int currentHour; int currentMinute; if (position == scheduleFromRow) { currentHour = Theme.autoNightDayStartTime / 60; currentMinute = (Theme.autoNightDayStartTime - currentHour * 60); } else { currentHour = Theme.autoNightDayEndTime / 60; currentMinute = (Theme.autoNightDayEndTime - currentHour * 60); } final TextSettingsCell cell = (TextSettingsCell) view; TimePickerDialog dialog = new TimePickerDialog(getParentActivity(), (view1, hourOfDay, minute) -> { int time = hourOfDay * 60 + minute; if (position == scheduleFromRow) { Theme.autoNightDayStartTime = time; cell.setTextAndValue(LocaleController.getString("AutoNightFrom", R.string.AutoNightFrom), String.format("%02d:%02d", hourOfDay, minute), true); } else { Theme.autoNightDayEndTime = time; cell.setTextAndValue(LocaleController.getString("AutoNightTo", R.string.AutoNightTo), String.format("%02d:%02d", hourOfDay, minute), true); } }, currentHour, currentMinute, true); showDialog(dialog); } else if (position == scheduleUpdateLocationRow) { updateSunTime(null, true); } }); return fragmentView; }
From source file:com.kncwallet.wallet.ui.SendCoinsFragment.java
private void showConfirmDialog(final SendRequest sendRequest) { final BigInteger amount = amountCalculatorLink.getAmount(); BigInteger fee = sendRequest.fee; BigInteger amountIncludingFee = amount.add(fee); View view = activity.getLayoutInflater().inflate(R.layout.dialog_transaction_fee, null); CurrencyTextView dialogCurrencyBtc = (CurrencyTextView) view.findViewById(R.id.currency_text_view_btc); dialogCurrencyBtc.setPrecision(btcPrecision, btcShift); dialogCurrencyBtc.setAmount(amountIncludingFee); final String suffix = DenominationUtil.getCurrencyCode(btcShift); dialogCurrencyBtc.setSuffix(suffix); CurrencyTextView dialogCurrencyLocal = (CurrencyTextView) view.findViewById(R.id.currency_text_view_local); if (exchangeRate != null && exchangeRate.rate != null) { final BigInteger localValue = WalletUtils.localValue(amountIncludingFee, exchangeRate.rate); dialogCurrencyLocal.setSuffix(exchangeRate.currencyCode); dialogCurrencyLocal.setPrecision(Constants.LOCAL_PRECISION, 0); dialogCurrencyLocal.setStrikeThru(Constants.TEST); dialogCurrencyLocal.setAmount(localValue); } else {/*w w w .j av a2s . com*/ dialogCurrencyLocal.setVisibility(View.GONE); } String toName = validatedAddress.label; if (toName == null) { toName = validatedAddress.address.toString(); LinearLayout currencyParent = (LinearLayout) view.findViewById(R.id.currency_parent); currencyParent.setOrientation(LinearLayout.VERTICAL); } String textViewToText = getString(R.string.dialog_transaction_to_user, toName); TextView textViewTo = (TextView) view.findViewById(R.id.text_view_trail); textViewTo.setText(textViewToText); final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox); KnCDialog.Builder builder = new KnCDialog.Builder(activity); builder.setTitle(getString(R.string.dialog_transaction_title, amountIncludingFee)).setView(view) .setPositiveButton(R.string.send_tab_text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (checkBox.isChecked()) { prefs.edit().putBoolean(Constants.PREFS_KEY_FEE_INFO, false).commit(); } commitSendRequest(sendRequest); } }).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { resetSendRequest(); } }).show(); }
From source file:plugin.google.maps.GoogleMaps.java
@SuppressWarnings("unused") private void showDialog(final JSONArray args, final CallbackContext callbackContext) { if (windowLayer != null) { return;/* w w w . j a v a 2 s . co m*/ } // window layout windowLayer = new LinearLayout(activity); windowLayer.setPadding(0, 0, 0, 0); LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); layoutParams.gravity = Gravity.TOP | Gravity.LEFT; windowLayer.setLayoutParams(layoutParams); // dialog window layer FrameLayout dialogLayer = new FrameLayout(activity); dialogLayer.setLayoutParams(layoutParams); //dialogLayer.setPadding(15, 15, 15, 0); dialogLayer.setBackgroundColor(Color.LTGRAY); windowLayer.addView(dialogLayer); // map frame final FrameLayout mapFrame = new FrameLayout(activity); mapFrame.setPadding(0, 0, 0, (int) (40 * density)); dialogLayer.addView(mapFrame); if (this.mPluginLayout != null && this.mPluginLayout.getMyView() != null) { this.mPluginLayout.detachMyView(); } ViewGroup.LayoutParams lParams = (ViewGroup.LayoutParams) mapView.getLayoutParams(); if (lParams == null) { lParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); } lParams.width = ViewGroup.LayoutParams.MATCH_PARENT; lParams.height = ViewGroup.LayoutParams.MATCH_PARENT; if (lParams instanceof AbsoluteLayout.LayoutParams) { AbsoluteLayout.LayoutParams params = (AbsoluteLayout.LayoutParams) lParams; params.x = 0; params.y = 0; mapView.setLayoutParams(params); } else if (lParams instanceof LinearLayout.LayoutParams) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) lParams; params.topMargin = 0; params.leftMargin = 0; mapView.setLayoutParams(params); } else if (lParams instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) lParams; params.topMargin = 0; params.leftMargin = 0; mapView.setLayoutParams(params); } mapFrame.addView(this.mapView); // button frame LinearLayout buttonFrame = new LinearLayout(activity); buttonFrame.setOrientation(LinearLayout.HORIZONTAL); buttonFrame.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM); LinearLayout.LayoutParams buttonFrameParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); buttonFrame.setLayoutParams(buttonFrameParams); dialogLayer.addView(buttonFrame); //close button LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f); TextView closeLink = new TextView(activity); closeLink.setText("Close"); closeLink.setLayoutParams(buttonParams); closeLink.setTextColor(Color.BLUE); closeLink.setTextSize(20); closeLink.setGravity(Gravity.LEFT); closeLink.setPadding((int) (10 * density), 0, 0, (int) (10 * density)); closeLink.setOnClickListener(GoogleMaps.this); closeLink.setId(CLOSE_LINK_ID); buttonFrame.addView(closeLink); //license button TextView licenseLink = new TextView(activity); licenseLink.setText("Legal Notices"); licenseLink.setTextColor(Color.BLUE); licenseLink.setLayoutParams(buttonParams); licenseLink.setTextSize(20); licenseLink.setGravity(Gravity.RIGHT); licenseLink.setPadding((int) (10 * density), (int) (20 * density), (int) (10 * density), (int) (10 * density)); licenseLink.setOnClickListener(GoogleMaps.this); licenseLink.setId(LICENSE_LINK_ID); buttonFrame.addView(licenseLink); webView.setVisibility(View.GONE); root.addView(windowLayer); //Dummy view for the back-button event FrameLayout dummyLayout = new FrameLayout(activity); /* this.webView.showCustomView(dummyLayout, new WebChromeClient.CustomViewCallback() { @Override public void onCustomViewHidden() { mapFrame.removeView(mapView); if (mPluginLayout != null && mapDivLayoutJSON != null) { mPluginLayout.attachMyView(mapView); mPluginLayout.updateViewPosition(); } root.removeView(windowLayer); webView.setVisibility(View.VISIBLE); windowLayer = null; GoogleMaps.this.onMapEvent("map_close"); } }); */ this.sendNoResult(callbackContext); }
From source file:android.support.v7.widget.ListPopupWindow.java
/** * <p>Builds the popup window's content and returns the height the popup * should have. Returns -1 when the content already exists.</p> * * @return the content's height or -1 if content already exists *//*ww w . j a v a 2 s.c o m*/ private int buildDropDown() { ViewGroup dropDownView; int otherHeights = 0; if (mDropDownList == null) { Context context = mContext; /** * This Runnable exists for the sole purpose of checking if the view layout has got * completed and if so call showDropDown to display the drop down. This is used to show * the drop down as soon as possible after user opens up the search dialog, without * waiting for the normal UI pipeline to do it's job which is slower than this method. */ mShowDropDownRunnable = new Runnable() { public void run() { // View layout should be all done before displaying the drop down. View view = getAnchorView(); if (view != null && view.getWindowToken() != null) { show(); } } }; mDropDownList = new DropDownListView(context, !mModal); if (mDropDownListHighlight != null) { mDropDownList.setSelector(mDropDownListHighlight); } mDropDownList.setAdapter(mAdapter); mDropDownList.setOnItemClickListener(mItemClickListener); mDropDownList.setFocusable(true); mDropDownList.setFocusableInTouchMode(true); mDropDownList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position != -1) { DropDownListView dropDownList = mDropDownList; if (dropDownList != null) { dropDownList.mListSelectionHidden = false; } } } public void onNothingSelected(AdapterView<?> parent) { } }); mDropDownList.setOnScrollListener(mScrollListener); if (mItemSelectedListener != null) { mDropDownList.setOnItemSelectedListener(mItemSelectedListener); } dropDownView = mDropDownList; View hintView = mPromptView; if (hintView != null) { // if a hint has been specified, we accomodate more space for it and // add a text view in the drop down menu, at the bottom of the list LinearLayout hintContainer = new LinearLayout(context); hintContainer.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams hintParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f); switch (mPromptPosition) { case POSITION_PROMPT_BELOW: hintContainer.addView(dropDownView, hintParams); hintContainer.addView(hintView); break; case POSITION_PROMPT_ABOVE: hintContainer.addView(hintView); hintContainer.addView(dropDownView, hintParams); break; default: Log.e(TAG, "Invalid hint position " + mPromptPosition); break; } // measure the hint's height to find how much more vertical space // we need to add to the drop down's height int widthSpec = MeasureSpec.makeMeasureSpec(mDropDownWidth, MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.UNSPECIFIED; hintView.measure(widthSpec, heightSpec); hintParams = (LinearLayout.LayoutParams) hintView.getLayoutParams(); otherHeights = hintView.getMeasuredHeight() + hintParams.topMargin + hintParams.bottomMargin; dropDownView = hintContainer; } mPopup.setContentView(dropDownView); } else { dropDownView = (ViewGroup) mPopup.getContentView(); final View view = mPromptView; if (view != null) { LinearLayout.LayoutParams hintParams = (LinearLayout.LayoutParams) view.getLayoutParams(); otherHeights = view.getMeasuredHeight() + hintParams.topMargin + hintParams.bottomMargin; } } // getMaxAvailableHeight() subtracts the padding, so we put it back // to get the available height for the whole window int padding = 0; Drawable background = mPopup.getBackground(); if (background != null) { background.getPadding(mTempRect); padding = mTempRect.top + mTempRect.bottom; // If we don't have an explicit vertical offset, determine one from the window // background so that content will line up. if (!mDropDownVerticalOffsetSet) { mDropDownVerticalOffset = -mTempRect.top; } } else { mTempRect.setEmpty(); } // Max height available on the screen for a popup. boolean ignoreBottomDecorations = mPopup.getInputMethodMode() == PopupWindow.INPUT_METHOD_NOT_NEEDED; final int maxHeight = mPopup.getMaxAvailableHeight(getAnchorView(), mDropDownVerticalOffset /*, ignoreBottomDecorations*/); if (mDropDownAlwaysVisible || mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { return maxHeight + padding; } final int childWidthSpec; switch (mDropDownWidth) { case ViewGroup.LayoutParams.WRAP_CONTENT: childWidthSpec = MeasureSpec.makeMeasureSpec( mContext.getResources().getDisplayMetrics().widthPixels - (mTempRect.left + mTempRect.right), MeasureSpec.AT_MOST); break; case ViewGroup.LayoutParams.MATCH_PARENT: childWidthSpec = MeasureSpec.makeMeasureSpec( mContext.getResources().getDisplayMetrics().widthPixels - (mTempRect.left + mTempRect.right), MeasureSpec.EXACTLY); break; default: childWidthSpec = MeasureSpec.makeMeasureSpec(mDropDownWidth, MeasureSpec.EXACTLY); break; } final int listContent = mDropDownList.measureHeightOfChildrenCompat(childWidthSpec, 0, DropDownListView.NO_POSITION, maxHeight - otherHeights, -1); // add padding only if the list has items in it, that way we don't show // the popup if it is not needed if (listContent > 0) otherHeights += padding; return listContent + otherHeights; }
From source file:plugin.google.maps.GoogleMaps.java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override//from ww w . j av a2s. c om public View getInfoContents(Marker marker) { String title = marker.getTitle(); String snippet = marker.getSnippet(); if ((title == null) && (snippet == null)) { return null; } JSONObject properties = null; JSONObject styles = null; String propertyId = "marker_property_" + marker.getId(); PluginEntry pluginEntry = this.plugins.get("Marker"); PluginMarker pluginMarker = (PluginMarker) pluginEntry.plugin; if (pluginMarker.objects.containsKey(propertyId)) { properties = (JSONObject) pluginMarker.objects.get(propertyId); if (properties.has("styles")) { try { styles = (JSONObject) properties.getJSONObject("styles"); } catch (JSONException e) { } } } // Linear layout LinearLayout windowLayer = new LinearLayout(activity); windowLayer.setPadding(3, 3, 3, 3); windowLayer.setOrientation(LinearLayout.VERTICAL); LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER; windowLayer.setLayoutParams(layoutParams); //---------------------------------------- // text-align = left | center | right //---------------------------------------- int gravity = Gravity.LEFT; int textAlignment = View.TEXT_ALIGNMENT_GRAVITY; if (styles != null) { try { String textAlignValue = styles.getString("text-align"); switch (TEXT_STYLE_ALIGNMENTS.valueOf(textAlignValue)) { case left: gravity = Gravity.LEFT; textAlignment = View.TEXT_ALIGNMENT_GRAVITY; break; case center: gravity = Gravity.CENTER; textAlignment = View.TEXT_ALIGNMENT_CENTER; break; case right: gravity = Gravity.RIGHT; textAlignment = View.TEXT_ALIGNMENT_VIEW_END; break; } } catch (Exception e) { } } if (title != null) { if (title.indexOf("data:image/") > -1 && title.indexOf(";base64,") > -1) { String[] tmp = title.split(","); Bitmap image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]); image = PluginUtil.scaleBitmapForDevice(image); ImageView imageView = new ImageView(this.cordova.getActivity()); imageView.setImageBitmap(image); windowLayer.addView(imageView); } else { TextView textView = new TextView(this.cordova.getActivity()); textView.setText(title); textView.setSingleLine(false); int titleColor = Color.BLACK; if (styles != null && styles.has("color")) { try { titleColor = PluginUtil.parsePluginColor(styles.getJSONArray("color")); } catch (JSONException e) { } } textView.setTextColor(titleColor); textView.setGravity(gravity); if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { textView.setTextAlignment(textAlignment); } //---------------------------------------- // font-style = normal | italic // font-weight = normal | bold //---------------------------------------- int fontStyle = Typeface.NORMAL; if (styles != null) { try { if ("italic".equals(styles.getString("font-style"))) { fontStyle = Typeface.ITALIC; } } catch (JSONException e) { } try { if ("bold".equals(styles.getString("font-weight"))) { fontStyle = fontStyle | Typeface.BOLD; } } catch (JSONException e) { } } textView.setTypeface(Typeface.DEFAULT, fontStyle); windowLayer.addView(textView); } } if (snippet != null) { //snippet = snippet.replaceAll("\n", ""); TextView textView2 = new TextView(this.cordova.getActivity()); textView2.setText(snippet); textView2.setTextColor(Color.GRAY); textView2.setTextSize((textView2.getTextSize() / 6 * 5) / density); textView2.setGravity(gravity); if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { textView2.setTextAlignment(textAlignment); } windowLayer.addView(textView2); } return windowLayer; }