16 small experience summaries for android development
16 small experience summaries of Android development, I hope it will be helpful to all friends who are engaged in Android development.
1. The return value of getTextSize in TextView is in pixels (px),
And setTextSize() is in sp.
So if you set it directly with the returned value, it will make an error. The solution is to use another form of setTextSize(), which can specify the unit:
setTextSize(int unit, int size) TypedValue.COMPLEX_UNIT_PX : Pixels TypedValue.COMPLEX_UNIT_SP : Scaled Pixels TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels
2. When inheriting from View, when drawing bitmap, you need to put the picture into the newly created drawable-xdpi, otherwise the drawing size will easily occur Change
3. Underline the text: textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
4. scrollView inherits from frameLayout, so you need to use frameLayout when using LayoutParams
5. In Android Several network programming methods:
(1) Socket and ServerSocket for TCP/IP
(2) DatagramSocket and DatagramPackage for UDP. What needs to be noted here is that considering that Android devices are usually handheld terminals, IPs are allocated along with Internet access. Not fixed. Therefore, development is a little different from ordinary Internet applications.
(3) HttpURLConnection for direct URL
(4) Google has integrated the Apache HTTP client and can use HTTP for network programming. For HTTP, Google has integrated Appache Http core and httpclient 4 versions, so pay special attention to the fact that Android does not support the httpclient 3. . Android can support Xmlrpc and Jsonrpc through open source packages such as Jackson. In addition, it can also use Ksoap2 to implement Webservice
(6) Directly use the WebView view component to display web pages. Developed based on WebView, Google has provided a web browser based on chrome-lite, which can directly browse the web.
6. TranslateAnimation(float from Value;
Float toXDelta, this parameter represents the difference between the animation end point and the current View X coordinate;
float fromYDelta, this parameter represents the difference between the animation start point and the current View Y coordinate;
float toYDelta ) This parameter represents the difference between the starting point of the animation and the Y coordinate of the current View;
If the view is at point A (x, y), then the animation moves from point B (x+fromXDelta, y+fromYDelta) to point C (x+toXDelta,y+toYDelta) point.
7.android provides several methods to access the UI thread in other threads.
Activity.runOnUiThread( Runnable ) View.post( Runnable ) View.postDelayed( Runnable, long )
Get a webpage from the Internet and display its source code in a TextView
package org.unique.async; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class NetworkActivity extends Activity{ private TextView message; private Button open; private EditText url; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.network); message= (TextView) findViewById(R.id.message); url= (EditText) findViewById(R.id.url); open= (Button) findViewById(R.id.open); open.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { connect(); } }); } private void connect() { PageTask task = new PageTask(this); task.execute(url.getText().toString()); } class PageTask extends AsyncTask<String, Integer, String> { // 可变长的输入参数,与AsyncTask.exucute()对应 ProgressDialog pdialog; public PageTask(Context context){ pdialog = new ProgressDialog(context, 0); pdialog.setButton("cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { dialog.cancel(); } }); pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { finish(); } }); pdialog.setCancelable(true); pdialog.setMax(100); pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pdialog.show(); } @Override protected String doInBackground(String... params) { try{ HttpClient client = new DefaultHttpClient(); // params[0]代表连接的url HttpGet get = new HttpGet(params[0]); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); long length = entity.getContentLength(); InputStream is = entity.getContent(); String s = null; if(is != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[128]; int ch = -1; int count = 0; while((ch = is.read(buf)) != -1) { baos.write(buf, 0, ch); count += ch; if(length > 0) { // 如果知道响应的长度,调用publishProgress()更新进度 publishProgress((int) ((count / (float) length) * 100)); } // 让线程休眠100ms Thread.sleep(100); } s = new String(baos.toByteArray()); } // 返回结果 return s; } catch(Exception e) { e.printStackTrace(); } return null; } @Override protected void onCancelled() { super.onCancelled(); } @Override protected void onPostExecute(String result) { // 返回HTML页面的内容 message.setText(result); pdialog.dismiss(); } @Override protected void onPreExecute() { // 任务启动,可以在这里显示一个对话框,这里简单处理 message.setText(R.string.task_started); } @Override protected void onProgressUpdate(Integer... values) { // 更新进度 System.out.println(""+values[0]); message.setText(""+values[0]); pdialog.setProgress(values[0]); } } }
8. Solution that Spinner cannot be used in dialog and tabhost
9. Eclipse associates JDK source code
(1). Point "window"-> "Preferences" -> "Java" -> "Installed JRES"
(2). At this time, the right side of "Installed JRES" is a list pane, which lists the JRE environments in the system. Select Your JRE, and then click "Edit..." on the side, a window (Edit JRE) will appear (3). Select this item of the rt.jar file: "c:program filesjavajre_1.5.0_06librt.jar" Expand it with the "+" sign on the left,
(4). After expansion, you can see "Source Attachment: (none)", click this item, click the button "Source Attachment..." on the right, and select your JDK directory "src.zip" file under
10.Unable to open sync connection!
Restart the USB debugging in the settings
11. The problem with setting the cursor position in EditText
When there are some preset texts in EditText, I want to move the cursor to the front. I used setSelection(0) at first, and found that I have a problem on Samsung P1000. After research, it was found that EditText.requestFocus() needs to be called first, and then setSelection(0). Otherwise, there will be problems on 2.x machines, but it will be fine on 3.x machines.
12. The Home button in Android is reserved by the system. You cannot use onKeyDown like monitoring the back button. However, you can add your own processing code based on some events of activity and view that will be triggered when the home button is pressed. Some people on the Internet said that it is possible. Use onAttachWindow to intercept the Home button, never tried it
13. When rendering with surfaceView, if you want other Views to appear when needed, you can put the surfaceView and other Views in the layout, and you can hide other views in normal times
14. Use android:imeOptinos to make some interface settings for the soft keyboard that comes with Android:
android:imeOptions="flagNoExtractUi" //So that the soft keyboard does not display in full screen and only takes up part of the screen
At the same time, this attribute also Can control the display content of the key in the lower right corner of the soft keyboard, which is the Enter key by defaultandroid:imeOptions="actionNone" //输入框右侧不带任何提示 android:imeOptions="actionGo" //右下角按键内容为'开始' android:imeOptions="actionSearch" //右下角按键为放大镜图片,搜索 android:imeOptions="actionSend" //右下角按键内容为'发送' android:imeOptions="actionNext" //右下角按键内容为'下一步' android:imeOptions="actionDone" //右下角按键内容为'完成'
15. Add shadow to TextView
<style name="Overlay"> <item name="android:paddingLeft">2dip</item> <item name="android:paddingBottom">2dip</item> <item name="android:textColor">#ffffff</item> <item name="android:textSize">12sp</item> <item name="android:shadowColor">#00ff00</item> <item name="android:shadowDx">5</item> <item name="android:shadowDy">3</item> <item name="android:shadowRadius">6</item> </style> <TextView android:id="@+id/test" android:layout_width="fill_parent" android:layout_height="wrap_content" style="@style/<span style="background-color: rgb(250, 250, 250); font-family: Helvetica, Tahoma, Arial, sans-serif; ">Overlay</span>" android:text="test" android:gravity="center" />
16. How to set the Chinese in TextView to bold?
在xml文件中使用android:textStyle=”bold” 可以将英文设置成粗体,但是不能将中文设置成粗体,将中文设置成粗体的方法是:
TextView tv = (TextView)findViewById(R.id.TextView01); TextPaint tp = tv.getPaint(); tp.setFakeBoldText(true);

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!
