編輯:關於Android編程
解決方案:
1、全局配置jdk1.8.0_45\bin(或cd進入bin目錄)
2、keytool -v -list -keystore 你的keystore路徑
3、輸入秘鑰庫口令:如果沒設置,這裡就是空,直接回車就進去了。
Add new device出現的問題:
Failed to deploy virtual device.
Unable to create virtual device.Connection timeout occurred.
解決方案:
當選擇Google Nexus 5 - 6.0.0 - API 23 - 1080x1920下載device失敗後,到C:\Users\用戶主目錄\AppData\Local\Genymobile\Genymotion\ova下看到genymotion_vbox86p_6.0_160114_090449.ova,大小卻是0KB,在C:\Users\用戶主目錄\AppData\Local\Genymobile\genymotion.log,打開該文件,找到類似“http://files2.genymotion.com/dists/6.0.0/ova/genymotion_vbox86p_6.0_160114_090449.ova”路徑,即您想要下載的鏡像文件URL;用迅雷去下載,下載完成後放到C:\Users\用戶主目錄\AppData\Local\Genymobile\Genymotion\ova;重新點擊Google Nexus 5 - 6.0.0 - API 23 - 1080x1920去下載,驗證安裝後即會顯示在設備列表中。單擊F5(Step Over),單行一個個方法執行
單擊F6(Step Into),單行執行
單擊F7(Step Out),不往下執行,回到上一行
單擊F8(Resume Program),跳出當前斷點
新浪微博SSO登錄,微信分享這些都需要簽名打包,才能看到效果,設置默認簽名文件為自己的簽名jks,這樣就不需要打包了。
在app目錄下添加你的.jks,然後app的build.gradle文件中的增加以下內容:
第一種:
android { signingConfigs { debug { storeFile file("你的.jks") storePassword 'android' keyAlias 'android' keyPassword 'android' } } }
第二種:
android { signingConfigs { release { storeFile file("你的.jks") storePassword 'android' keyAlias 'android' keyPassword 'android' } } buildTypes { debug { signingConfig signingConfigs.release } } }
這樣編譯出來的debug版本直接用的是你的正式簽名
protected boolean isVisible; @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (getUserVisibleHint()) { isVisible = true; onVisible(); } else { isVisible = false; onInvisible(); } } protected void onVisible() { lazyLoad(); } protected void lazyLoad() { if (!isVisible) { return; } getData(); } protected void onInvisible() { }
File | Settings | Editor|File and Code Templates|Includes|File Header
/** * Created by ${USER} on ${DATE}. */
輸入我們想要設置的注釋模板
getPositionForSection()根據分類列的索引號獲得該序列的首個位置
getSectionForPosition()通過該項的位置,獲得所在分類組的索引號
textView.setTextColor(Color.parseColor("#FFFFFF")); //或者 ContextCompat.getColor(context, R.color.color_name)
private void showPopupMenu(View v) { final View bgView = View.inflate(DemoApplication.getContext(), R.layout.demo_popup_window_bg, null); bgView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hidePopupWindow(); } }); if (mPopupBackground == null) { mPopupBackground = new PopupWindow(bgView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); } mPopupBackground.showAtLocation(v, Gravity.BOTTOM, 0, 0); }
v:父布局
demo_popup_window_bg.xml
view的onFinishInflate()何時調用的?
當View中所有的子控件均被映射成xml後觸發;
MyView mv = (MyView)View.inflate (context,R.layout.my_view,null);
當加載完成xml後,就會執行那個方法;
我們一般使用View的流程是在onCreate中使用setContentView來設置要顯示Layout文件或直接創建一個View,在當設置了ContentView之後系統會對這個View進行解析,然後回調當前視圖View中的onFinishInflate方法。只有解析了這個View我們才能在這個View容器中獲取到擁有Id的組件,同樣因為系統解析完View之後才會調用onFinishInflate方法,所以我們自定義組件時可以onFinishInflate方法中獲取指定子View的引用。
MainFragment點擊
public void onItemClick(AdapterView adapterView, View view, int position, long id) { ((MainActivity) getActivity()).showImageFragment(true, mData.get(position).get("title").toString(), mData.get(position).get("imgUrl").toString()); }
MainActivity
public void showImageFragment(boolean show, String imgTxt, String imgUrl) { // showActionbarWithTabs(!show); if (show) { getSupportFragmentManager().beginTransaction() .show(imageDetailFragment).commit(); imageDetailFragment.setImgData(imgTxt, imgUrl); } else { getSupportFragmentManager().beginTransaction() .hide(imageDetailFragment).commit(); } }
不同主題下需要把顏色,數值寫成attr屬性
xml裡,我們可以簡單的引用attr屬性值
android:background="?attr/colorPrimary"
代碼獲取
TypedValue typedValue = new TypedValue(); mContext.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true); int colorPrimary = typedValue.data;//value.data裡面存儲著的就是獲取到的colorPrimary的值
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "400-036-1977")); // intent.setAction(Intent.ACTION_CALL);// 直接撥號 intent.setAction(Intent.ACTION_DIAL);// 撥號盤 startActivity(intent);
http://wuxiaolong.me/2015/08/10/Drawable-to-Bitmap/
final ProgressDialog progress = new ProgressDialog(LoginActivity.this); progress.setMessage("請稍等..."); progress.setCanceledOnTouchOutside(false); progress.show(); progress.dismiss();
毫秒Calendar.getInstance().getTimeInMillis()和System.currentTimeMillis()
@Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { //相當於Fragment的onResume } else { //相當於Fragment的onPause } }
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); getActivity(); if (resultCode == Activity.RESULT_OK && requestCode == AppUtils.REQUEST_CODE_ISLOGIN) { // 檢查是否完善資料 if (AppUtils.getSharedPreferences(getActivity()).getBoolean( "hasPersonalData", false)) { // 取本地存取是否完善資料,完善直接提示咨詢對話框 consultationDialog(); } else { getCheckPersonalData(); } } } startActivityForResult(intent, AppConfig.REQUEST_CODE_DIALOGUE);// 不是調用 getActivity().startActivityForResult()。
getDimension方法獲取到資源文件中定義的dimension值。
Resources res = getResources(); float fontSize = res.getDimension(R.dimen.font_size);
1、創建數組後,通過循環對數組賦值。
例如代碼:
int [] nums = new int [100];
for(int i=0;i<10;i++){
nums[i] = i;
}
2、例如代碼:
int [] nums = {0,1,2,3,4,5,6,7,8,9};
3、int [] nums = new int[]{0,1,2,3,4,5,6,7,8,9};
Fragment mBeforeFragment = new Fragment(); public void switchFragment(Fragment currentFragment) { if (currentFragment.isAdded()) { getSupportFragmentManager().beginTransaction().hide(mBeforeFragment).show(currentFragment).commit(); } else { getSupportFragmentManager().beginTransaction().hide(mBeforeFragment).add(R.id.container, currentFragment).commit(); } mBeforeFragment = currentFragment; }
調用:
switchFragment(HomeFragment.newInstance());
HomeFragment
public static HomeFragment homeFragment = null; public static HomeFragment newInstance() { if (homeFragment == null) { homeFragment = new HomeFragment(); } return homeFragment; }
//文本類型,多為大寫、小寫和數字符號。 android:inputType="none" android:inputType="text" android:inputType="textCapCharacters" 字母大寫 android:inputType="textCapWords" 首字母大寫 android:inputType="textCapSentences" 僅第一個字母大寫 android:inputType="textAutoCorrect" 自動完成 android:inputType="textAutoComplete" 自動完成 android:inputType="textMultiLine" 多行輸入 android:inputType="textImeMultiLine" 輸入法多行(如果支持) android:inputType="textNoSuggestions" 不提示 android:inputType="textUri" 網址 android:inputType="textEmailAddress" 電子郵件地址 android:inputType="textEmailSubject" 郵件主題 android:inputType="textShortMessage" 短訊 android:inputType="textLongMessage" 長信息 android:inputType="textPersonName" 人名 android:inputType="textPostalAddress" 地址 android:inputType="textPassword" 密碼 android:inputType="textVisiblePassword" 可見密碼 android:inputType="textWebEditText" 作為網頁表單的文本 android:inputType="textFilter" 文本篩選過濾 android:inputType="textPhonetic" 拼音輸入 //數值類型 android:inputType="number" 數字 android:inputType="numberSigned" 帶符號數字格式 android:inputType="numberDecimal" 帶小數點的浮點格式 android:inputType="phone" 撥號鍵盤 android:inputType="datetime" 時間日期 android:inputType="date" 日期鍵盤 android:inputType="time" 時間鍵盤
(1)ImageView.ScaleType.center:圖片位於視圖中間,但不執行縮放。
(2)ImageView.ScaleType.CENTER_CROP 按統一比例縮放圖片(保持圖片的尺寸比例)便於圖片的兩維(寬度和高度)等於或者大於相應的視圖的維度
(3)ImageView.ScaleType.CENTER_INSIDE按統一比例縮放圖片(保持圖片的尺寸比例)便於圖片的兩維(寬度和高度)等於或者小於相應的視圖的維度
(4)ImageView.ScaleType.FIT_CENTER縮放圖片使用center
(5)ImageView.ScaleType.FIT_END縮放圖片使用END
(6)ImageView.ScaleType.FIT_START縮放圖片使用START
(7)ImageView.ScaleType.FIT_XY縮放圖片使用XY
(8)ImageView.ScaleType.MATRIX當繪制時使用圖片矩陣縮放
/** * 發送短信 * @param smsBody */ private void sendSMS(String smsBody) { //Uri smsToUri = Uri.parse("smsto:10000"); //如果想指定發送人 Uri smsToUri = Uri.parse("smsto:"); Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri); intent.putExtra("sms_body", smsBody); startActivity(intent); }
Intent intent = new Intent( "android.intent.action.VIEW"); intent.setData(Uri .parse("market://details?id=com.adobe.flashplayer")); startActivity(intent);
//檢測系統中是否已經安裝了adobe flash player插件,插件的packageName是com.adobe.flashplayer: private boolean check() { PackageManager pm = getPackageManager(); ListinfoList = pm .getInstalledPackages(PackageManager.GET_SERVICES); for (PackageInfo info : infoList) { if ("com.adobe.flashplayer".equals(info.packageName)) { return true; } } return false; } private void isAvilible(String packageName) { PackageInfo packageInfo; try { packageInfo = this.getPackageManager().getPackageInfo(packageName, 0); } catch (NameNotFoundException e) { packageInfo = null; e.printStackTrace(); } if (packageInfo != null) { //1、通過包名 Intent intent = new Intent(); intent = getPackageManager().getLaunchIntentForPackage(packageName); startActivity(intent); //2、通過類名: Intent intent=new Intent(); intent.setComponent(new ComponentName(packageName, "com.joe.internet.Main")); startActivity(intent); } }
new AlertDialog.Builder(this) .setTitle("choice") .setItems(new String[] { "選擇1", "選擇2", "選擇3", "選擇4" }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MyContentActivity.this, which + "", Toast.LENGTH_SHORT) .show(); } }).show();
progress_rotate:
xml
style
anim
public String Md5(String plainText) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString().toUpperCase();// 32位的加密(轉成大寫) buf.toString().substring(8, 24);// 16位的加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub Intent goIntent = new Intent(); goIntent.setClass(LauncherActivity.this, DemoActivity.class); startActivity(goIntent); } }, 3 * 1000); }
new Handler().postDelayed(new Runnable() { @Override public void run() { startActivity(new Intent(SplashScreen.this, DomobSampleActivity.class)); finish(); } }, 1000);
Listlist = new ArrayList (); for (int i = 0; i < 10; i++) { list.add(i); } Collections.shuffle(list); for (int v : list) { Log.d("wxl", "V===" + v); }
或:
Random random = new Random(); int ran = random.nextInt(keywordsList.size()); String tmp = keywordsList.get(ran).get("keyword").toString();
android:state_pressed
如果是true,當被點擊時顯示該圖片,如果是false沒被按下時顯示默認。
android:state_focused
true,獲得焦點時顯示;false,沒獲得焦點顯示默認。
android:state_selected
true,當被選擇時顯示該圖片;false,當未被選擇時顯示該圖片。
android:state_checkable
true,當 能使用時顯示該圖片;false,當CheckBox不能使用時顯示該圖片。
android:state_checked
true,當CheckBox選中時顯示該圖片;false,當CheckBox為選中時顯示該圖片。
android:state_enabled
true,當該組件能使用時顯示該圖片;false,當該組件不能使用時顯示該圖片。
android:state_window_focused
true,當此activity獲得焦點在最前面時顯示該圖片;false,當沒在最前面時顯示該圖片。
public class LinedEditText extends EditText { private Paint linePaint; private float margin; private int paperColor; public LinedEditText(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); this.linePaint = new Paint(); } @Override protected void onDraw(Canvas paramCanvas) { paramCanvas.drawColor(this.paperColor); int i = getLineCount();// 得到總的行數 int j = getHeight();// 獲得TextView的高度 int k = getLineHeight();// 獲得TextView的行高 int m = j / k + 1;// 總的線數 if (i < m) i = m; int n = getCompoundPaddingTop(); Log.d("wxl", "n----" + n); paramCanvas.drawLine(0.0F, n, getRight(), n, this.linePaint); for (int i2 = 0;; i2++) { if (i2 >= i) { setPadding(10 + (int) this.margin, 0, 0, 0); super.onDraw(paramCanvas); paramCanvas.restore(); return; } n += k; paramCanvas.drawLine(0.0F, n, getRight(), n, this.linePaint); paramCanvas.save(); } } }
主要工作就是重載onDraw方法,利用從TextView繼承下來的getLineCount函數獲取文本所占的行數,以及getLineBounds來獲取特定行的基准高度值,而且這個函數第二個參數會返回此行的“外包裝”值。再利用這些值繪制這一行的線條。為了讓界面的View使用自定義的EditText類,必須在配置文件中進行設置
public static void hideSoftInput(Activity activity) { if (activity.getCurrentFocus() != null) ((InputMethodManager) activity .getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(activity.getCurrentFocus() .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); }
一進入activity就彈出鍵盤
android:windowSoftInputMode="adjustResize" android:windowSoftInputMode="adjustPan|stateAlwaysVisible"
第一個軟鍵盤和輸入框會完全分離,而第二個輸入框還是會被軟鍵盤蓋住一點點
而且第二個要把兩個屬性疊加起來,為什麼要疊加起來呢,因為如果只用adjustPan 的話需要點擊輸入框才會彈出軟鍵盤
在 AndroidMainfest.xml中選擇哪個activity,設置windowSoftInputMode屬性為
adjustUnspecified|stateHidden android:windowSoftInputMode="adjustUnspecified|stateHidden"
windowSoftInputMode各值的含義:
stateUnspecified:軟鍵盤的狀態並沒有指定,系統將選擇一個合適的狀態或依賴於主題的設置
stateUnchanged:當這個activity出現時,軟鍵盤將一直保持在上一個activity裡的狀態,無論是隱藏還是顯示
stateHidden:用戶選擇activity時,軟鍵盤總是被隱藏
stateAlwaysHidden:當該Activity主窗口獲取焦點時,軟鍵盤也總是被隱藏的
stateVisible:軟鍵盤通常是可見的
stateAlwaysVisible:用戶選擇activity時,軟鍵盤總是顯示的狀態
adjustUnspecified:默認設置,通常由系統自行決定是隱藏還是顯示
adjustResize:該Activity總是調整屏幕的大小以便留出軟鍵盤的空間
adjustPan:當前窗口的內容將自動移動以便當前焦點從不被鍵盤覆蓋和用戶能總是看到輸入內容的部分
http://wuxiaolong.me/2013/07/09/shape/
public String getVersionName(Context context) { PackageManager manager = context.getPackageManager(); String packageName = context.getPackageName(); try { PackageInfo info = manager.getPackageInfo(packageName, 0); return info.versionName; } catch (NameNotFoundException e) { return "1.0"; } }
TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String imsi = mTelephonyMgr.getSubscriberId(); String imei = mTelephonyMgr.getDeviceId(); Log.i("wxl", "imsi="+imsi);為null Log.i("wxl", "imei="+imei); 另外不要忘了在AndroidManifest.xml中加上讀取手機狀態的權限
public class Log { private static final String TAG = "wxl"; private static final boolean LOG = true; public static void i(String msg) { if (LOG) android.util.Log.i(TAG , msg); } public static void d(String msg) { if (LOG) android.util.Log.d(TAG , msg); } public static void w(String msg) { if (LOG) android.util.Log.w(TAG , msg); } public static void w(String msg, Throwable throwable) { if (LOG) android.util.Log.w(TAG , msg, throwable); } public static void v(String msg) { if (LOG) android.util.Log.v(TAG , msg); } public static void e(String msg) { android.util.Log.e(TAG , msg); } public static void e(String msg, Throwable throwable) { android.util.Log.e(TAG , msg, throwable); } }
參數1:向後台任務的執行方法傳遞參數的類型 ; 參數2:在後台任務執行過程中,要求主UI線程處理中間狀態,通常是一些UI處理中傳遞的參數類型; 參數3:後台任務執行完返回時的參數類型。 private class MyAsyncTask extends AsyncTask{ // 實現抽象方法doInBackground(),代碼將在後台線程中執行,由execute()觸發 protected Void doInBackground(Integer... params) { return null; } // 任務啟動,可以在這裡顯示一個對話框,這裡簡單處理 protected void onPreExecute() { super.onPreExecute(); } // 取消 protected void onCancelled() { super.onCancelled(); } // 定義後台進程執行完後的處理 protected void onPostExecute(Void result) { super.onPostExecute(result); Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show(); } // 更新進度,在UI主線程執行的內容,將item加入list中。方法中的參數為范式方式,實質為數組,由於我們只傳遞了item一個String,要獲取,為values[0] protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); } }
調用:
1
new MyAsyncTask().execute(參數1);// 創建後台任務的對象
public boolean checkNetworkInfo() { ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // mobile 3G Data Network State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) .getState(); // wifi State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState(); // 如果3G網絡和wifi網絡都未連接,且不是處於正在連接狀態 則進入Network Setting界面 由用戶配置網絡連接 if (mobile == State.CONNECTED || mobile == State.CONNECTING) return true; if (wifi == State.CONNECTED || wifi == State.CONNECTING) return true; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getResources().getString(R.string.no_network)) .setCancelable(false) .setPositiveButton( getResources().getString(R.string.configuration), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // 進入無線網絡配置界面 startActivity(new Intent( Settings.ACTION_WIRELESS_SETTINGS)); MainActivity.this.finish(); } }) .setNegativeButton(getResources().getString(R.string.quit), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MainActivity.this.finish(); } }); builder.show(); return false; }
代碼判斷調用:
// 檢查網絡狀態 if (!checkNetworkInfo()) { return; }
讓數據接受網頁的格式
URLEncoder.encode(String s); 網址請求中文解析 …代表省略號
網址請求帶中文
URLEncoder.encode(content, "utf-8")
android:textStyle=”bold”
(網上查XML不能將中文設置成粗體,只能通過Java code。Android 2.2 可以通過XML將中文設置成粗體)
TextView tv = (TextView)findViewById(R.id.TextView01); TextPaint tp = tv.getPaint(); tp.setFakeBoldText(true);
(1)viewHolder.title.setText(Html.fromHtml("" + listTitle.get(position).get("title") + "")); (2)TextView.setText(Html.fromHtml("hello"));
textView.setBackgroundResource(R.drawable.bg_menu_1);設置背景圖片 textView.setBackgroundColor(0xffffffff); setImageResource與xml中的src的屬性才是相匹配的,而setBackgroundResource是與xml中的background屬性相匹配 的 holder.chat_sound_iv_right.setBackgroundResource(0);//沒有圖片
用法如下: 在xml中 android:ellipsize = "end" 省略號在結尾 android:ellipsize = "start" 省略號在開頭 android:ellipsize = "middle" 省略號在中間 android:ellipsize = "marquee" 跑馬燈 最好加一個約束android:singleline = "true" 跑馬燈 android:singleLine="true" android:ellipsize="marquee" android:focusableInTouchMode="true" android:focusable="true" android:marqueeRepeatLimit="marquee_forever" android:singleLine=true 表示使用單行文字,多行文字也就無所謂使用Marquee效果了。 android:marqueeRepeatLimit,設置走馬燈滾動的次數。 android:ellipsize,設置了文字過長時如何切斷文字,可以有none, start,middle, end, 如果使用走馬燈效果則設為marquee. android:focusable,Android的缺省行為是在控件獲得Focus時才會顯示走馬燈效果
方法一:
private DecimalFormat df; df = new DecimalFormat("0.0"); float data; df.format(data);//返回值
方法二:
double juli = 1569; String result = String.format("%.1f", juli/1000);
android:button=”@null” 去除RadioButton前面的圓點
android:background=”@drawable/radio” 使用定義的樣式
%d (表示整數)
%f (表示浮點數)
%s (表示字符串)
txt.setText(String.format (“被替換%1$s”,”替換內容”));
Drawable drawable = getResources().getDrawable(R.drawable.ji_dot_nor); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight()); textView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null); 說明:setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom) 意思是設置Drawable顯示在text的左、上、右、下位置。(Textview、Button都可以)
SpannableString spannableString = new SpannableString(str); spannableString.setSpan(new ClickableSpan() { public void onClick(View view) { // Intent intent = new Intent(ApkTest.this, Apk.class); Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "15261589767")); startActivity(intent); } }, 0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); TextView.setText(spannableString); TextView.setMovementMethod(LinkMovementMethod.getInstance());
來設置超鏈接、顏色、字體等屬性
String title =”123456”; SpannableString titleStr = new SpannableString(title); titleStr.setSpan(new ForegroundColorSpan(Color.RED), 0, titleStr.length(), 0); textView.setText(titleStr);
寫在TextView裡,實現圖片+文字
DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); displayMetrics.widthPixels + "x" + displayMetrics.heightPixels;
Button
linearLayout = (LinearLayout) findViewById(R.id.linearLayout2); LayoutParams layoutParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1);//1均分屬性 layoutParams.setMargins(10, 10, 10, 10); Button button = new Button(MainActivity.this); button.setLayoutParams(layoutParams); linearLayout.addView(button);
TextView
private TextView overlay; private void initOverlay() { LayoutInflater inflater = LayoutInflater.from(this); overlay = (TextView) inflater.inflate(R.layout.overlay, null); overlay.setVisibility(View.INVISIBLE); WindowManager.LayoutParams lp = new WindowManager.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, PixelFormat.TRANSLUCENT); WindowManager windowManager = (WindowManager) this .getSystemService(Context.WINDOW_SERVICE); windowManager.addView(overlay, lp); }private LinearLayout.LayoutParams layoutParams = null; private LinearLayout.LayoutParams btnParmas; layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins( (int) getResources().getDimension( R.dimen.lable_left), 0, 0, 0); btnParmas = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, (int) getResources().getDimension( R.dimen.lable_height)); for (int i = 0; i < lables.length; i++) { LinearLayout linearLayout = new LinearLayout(activity); lableColor = random.nextInt(lableColors.length); Button lable = new Button(activity); lable.setText(lables[i]); lable.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL); lable.setTextSize(getResources().getDimension( R.dimen.lable)); lable.setTextColor(getResources().getColor( R.color.white)); lable.setBackgroundResource(lableColors[i]); linearLayout.addView(lable, btnParmas); holder.play_lables.addView(linearLayout, layoutParams); }
editText1.addTextChangedListener(watcher); TextWatcher watcher = new TextWatcher() { public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } public void afterTextChanged(Editable arg0) { } };
AndroidManifest加入 android:configChanges="orientation|keyboardHidden"
獲取屏幕方向
Configuration newConfig = getResources().getConfiguration(); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){ //橫屏 }else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ //豎屏 }else if(newConfig.hardKeyboardHidden == Configuration.KEYBOARDHIDDEN_NO){ //鍵盤沒關閉。屏幕方向為橫屏 }else if(newConfig.hardKeyboardHidden == Configuration.KEYBOARDHIDDEN_YES){ //鍵盤關閉。屏幕方向為豎屏 }
private ListgetData() { List data = new ArrayList (); data.add("123"); data.add("345"); data.add("456"); data.add("567"); return data; }
private List
清除數據:
data.clear(); listView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1,getData()));
LinkedListlist = new LinkedList (); list.addFirst("000");
public boolean isMobileNO(String mobiles) { String expression = "((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))"; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(mobiles); Log.d("wxl", matcher.matches() + ""); return matcher.matches(); }
public boolean isNumber(String str) { java.util.regex.Pattern pattern=java.util.regex.Pattern.compile("[0-9]*"); java.util.regex.Matcher match=pattern.matcher(str); if(match.matches()==false) { return false; } else { return true; } }
SharedPreferences sharedPreferences = getSharedPreferences("test", Context.MODE_PRIVATE); Editor editor = sharedPreferences.edit();//獲取編輯器 editor.putString("name", "張三"); editor.putInt("age", 24); editor.putBoolean("AutoLogin", false); editor.commit();//提交修改
SharedPreferences sharedPreferences = getSharedPreferences("test", Context.MODE_PRIVATE); //getString()第二個參數為缺省值,如果preference中不存在該key,將返回缺省值 String name = sharedPreferences.getString("name", ""); int age = sharedPreferences.getInt("age", 1); boolean autoLogin= sharedPreferences. getBoolean("AutoLogin", false);
ActivityPage
Intent intent = new Intent(ActivityPage.this, Player.class); //保存信息 Bundle mBundle = new Bundle(); mBundle.putString("realname ", realname); intent.putExtras(mBundle);
Player接受
realname = this.getIntent().getStringExtra("realname"); Intent intent = new Intent(); intent.setClass(HomeActivity.this, CompanyActivity.class); intent.putExtra("mCompanySupply", mCompanySupply); startActivity(intent); CompanyActivity.class: ArrayListmCompanySupply = (ArrayList ) getIntent() .getSerializableExtra("mCompanySupply");
A頁面:
private static final int REQUEST_CODE_A = 0; private static final int RESULT_CODE_B = 0; Intent intent = new Intent(); Bundle bundle = new Bundle(); intent.setClass(MainActivity.this, TestBActivity.class); bundle.putString("msg", textView.getText().toString()); intent.putExtras(bundle); startActivityForResult(intent, REQUEST_CODE_A); protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_A && resultCode == RESULT_OK) { String str=data.getExtras().getString("result"); } }
B頁面
private static final int RESULT_CODE_B = 0; Intent intent = new Intent(); intent.putExtra("result", textView.getText().toString()); setResult(RESULT_OK, intent); finish(); public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { Intent intent = new Intent(); intent.putExtra("result", "直接返回"); setResult(RESULT_OK, intent); this.finish(); return true; } else { return super.onKeyDown(keyCode, event); } }
Intent intent = new Intent(); intent.putStringArrayListExtra("mSelectedPhotos", mSelectedPhotos); setResult(RESULT_OK, intent); ArrayListmSelectedPhotos = (ArrayList ) intent .getStringArrayListExtra("mSelectedPhotos");
private static Boolean isExit = false; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (isExit == false) { isExit = true; Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show(); new Timer().schedule(new TimerTask() { @Override public void run() { isExit = false; } }, 2000); } else { finish(); System.exit(0); } } return false; }
或者
@Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { long secondTime = System.currentTimeMillis(); if (secondTime - firstTime > 800) {//如果兩次按鍵時間間隔大於800毫秒,則不退出 Toast.makeText(MainActivity.this, "再按一次退出程序...", Toast.LENGTH_SHORT).show(); firstTime = secondTime;//更新firstTime return true; } else { System.exit(0);//否則退出程序 } } return super.onKeyUp(keyCode, event); }
TranslateAnimation left, right; right = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -1f, Animation.RELATIVE_TO_PARENT, -2f, Animation.RELATIVE_TO_PARENT, 0f, Animation.RELATIVE_TO_PARENT, 0f); left = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -2f, Animation.RELATIVE_TO_PARENT, -1f, Animation.RELATIVE_TO_PARENT, 0f, Animation.RELATIVE_TO_PARENT, 0f); right.setDuration(25000); left.setDuration(25000); right.setFillAfter(true); left.setFillAfter(true); right.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { runImage.startAnimation(left); } }); left.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { runImage.startAnimation(right); } }); runImage.startAnimation(right);
res下anim
animlayout.xml
cycle_7.xml
(2)java代碼
Animation shake = AnimationUtils.loadAnimation( MainActivity.this, R.anim.animlayout); btn.setAnimation(shake);
搶紅包,先看效果圖~實現自動搶紅包,解決問題有兩點:一:如何實時監聽發紅包的事件二:如何在紅包到來的時候自動進入頁面並自動點擊紅包一、如何獲取紅包到來的事件為了獲取紅包到
Android中有兩種主要方式使用Service,通過調用Context的startService方法或調用Context的bindService方法,本文只探討純sta
有時候你把手機接到電腦上調試時,Android Studio總是提示你重啟ADB,但是你點重啟後,立馬又跳出那個提示重啟的對話框。會再跳出提示對話框是因為你ADB重啟沒有
前面文章講述的都是隨手拍中圖像處理的操作,此篇文章主要講述GridView控件實現添加本地圖片並顯示.主要是關於GridView控件的基本操作,通常可以通過自定義繼承Ba