Summary of common Android programming skills

  • 2020-11-03 22:35:48
  • OfStack

This article provides examples of common Android programming techniques. To share for your reference, the details are as follows:

1. When logging in, if the input is wrong, the input box will vibrate left and right, indicating that the input is wrong
Prepare an anim folder under res containing two files, ES7en_login_shake.xml and ES11en_ES12en_ES13en_7.xml,

main_login_shake.xml is as follows:


<?xml version="1.0" encoding="utf-8"?> 
<translate 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:fromXDelta="0" 
  android:toXDelta="10" 
  android:duration="1000" 
  android:interpolator="@anim/main_login_cycle_7" />

main_login_cycle_7.xml is referred to in the above file as follows:


<?xml version="1.0" encoding="utf-8"?> 
<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android" android:cycles="7" /> 

So what these two pieces of code mean is that in one second or something, the x coordinate goes from zero to ten shakes seven times

Look at the java code:


shakeanim = AnimationUtils.loadAnimation(this,R.anim.main_login_shake);
btn_login.setOnClickListener(new OnClickListener() { 
  @Override 
  public void onClick(View v) { 
   boolean ready = true; 
   String username=et_username.getText().toString(); 
   String password=et_password.getText().toString(); 
   if (!username.matches("^\\w{1,}+$")) { 
    ready = false; 
    et_username.startAnimation(shakeanim); 
   } 
   if (!password.matches("^\\w{1,}+$")) { 
    ready = false; 
    et_password.startAnimation(shakeanim); 
   } 
   if(selectClinic==null){ 
    ready = false; 
    et_clinic.startAnimation(shakeanim); 
   } 
   if (ready) { 
    loginStart(username,password,Long.parseLong(selectClinic.get("id").toString()),Integer.parseInt(selectClinic.get("type_id").toString()));
   } 
  } 
});

2. When a dialog box is needed in many places in an Activity, it can be done as follows:


showDialog(R.id.wait_edit_arriveltime); 
showDialog(R.id.wait_edit_yuyuedata); 
showDialog(R.id.wait_edit_close); 
......
protected Dialog onCreateDialog(int id) { 
  Dialog dialog = null; 
  switch (id) { 
  case R.id.wait_edit_yuyuedata: 
    DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
     @Override 
     public void onDateSet(DatePicker datePicker,int year, int month, int dayOfMonth) {
      wait_edit_yuyuedata.setText(dayOfMonth + "/"+(month+1)+"/"+year);
     } 
    }; 
    dialog = new DatePickerDialog(this, dateListener, Integer.parseInt(app.getAppointedDate().split("/")[2]), Integer.parseInt(app.getAppointedDate().split("/")[1]), Integer.parseInt(app.getAppointedDate().split("/")[0])); 
    break; 
  case R.id.wait_edit_arriveltime: 
   TimePickerDialog.OnTimeSetListener timeListener = new TimePickerDialog.OnTimeSetListener() {
    @Override 
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
     wait_edit_arriveltime.setText(hourOfDay+":"+minute); 
    } 
   }; 
   dialog = new TimePickerDialog(this, timeListener, Integer.parseInt(app.getEstimateArriveTime().split(":")[0]), Integer.parseInt(app.getEstimateArriveTime().split(":")[1]), true);
   break; 
  case R.id.wait_edit_close: 
   AlertDialog.Builder builder = new AlertDialog.Builder(EditWaitActivity.this);
   builder.setTitle(" Are you sure you want to give up editing? "); 
   builder.setPositiveButton(" determine ",new DialogInterface.OnClickListener() {
    @Override 
    public void onClick(DialogInterface arg0, int arg1) { 
     EditWaitActivity.this.finish(); 
    }}); 
   builder.setNegativeButton(" cancel ",new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog,int whichButton) {
    } 
   }); 
   builder.show(); 
   break; 
  default: 
   break; 
  } 
  return dialog; 
}

3. Standard adapter format. Write in this format


public class MyAdapter extends BaseAdapter{ 
 Context context; 
 PageRecord<Appointment> data; 
 private ViewHolder tempHolder; 
 private View tempView; 
 public MyAdapter(Context context,PageRecord<Appointment> data){ 
  this.context = context; 
  this.data = data; 
 } 
 public View getView(int position, View convertView, ViewGroup parent) { 
  final ViewHolder holder; 
  Appointment app = data.getResultSet().get(position); 
  if(convertView==null){ 
   convertView=LayoutInflater.from(context).inflate(R.layout.item, null); 
   holder=new ViewHolder(convertView); 
   convertView.setTag(holder); 
  }else{ 
   holder=(ViewHolder) convertView.getTag(); 
  } 
  tempHolder = holder; 
  tempView = convertView; 
  holder.setData(app); 
  return convertView; 
 } 
 public long getItemId(int position) { 
  return position; 
 } 
 public Object getItem(int position) { 
  return data.getResultSet().get(position); 
 } 
 public int getCount() { 
  return data.getResultSet()==null?0:data.getResultSet().size(); 
 } 
 public void setData(PageRecord<Appointment> data){ 
  this.data = data; 
  this.notifyDataSetChanged(); 
  tempView.invalidate(); 
 } 
 /** 
  *  redraw  
  * @param app 
  */ 
 public void redraw(Appointment app){ 
  tempHolder.timeView.setText(app.getAppointedDate()+" "+app.getEstimateArriveTime()); 
  tempHolder.nameView.setText(app.getPatient().getNameEN()); 
  tempHolder.doctorView.setText(app.getMo().getNameEN()); 
  tempView.invalidate(); 
 } 
 private class ViewHolder{ 
  private TextView timeView; 
  private TextView nameView; 
  private TextView doctorView; 
  public ViewHolder(View convertView){ 
   timeView = (TextView) convertView.findViewById(R.id.yuyuetime);
   nameView = (TextView) convertView.findViewById(R.id.yuyuename);
   doctorView = (TextView) convertView.findViewById(R.id.doctorname);
  } 
  public void setData(Appointment app){ 
   timeView.setText(app.getAppointedDate()+" "+app.getEstimateArriveTime()); 
   nameView.setText(app.getPatient().getNameEN());
   doctorView.setText(app.getMo().getNameEN());
  } 
 } 
}

4. Two ways to get screen resolution


//  methods 1 Android Get the width and height of the screen 
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
//  methods 2
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
float width=dm.widthPixels*dm.density;
float height=dm.heightPixels*dm.density;

Print results: width: 320.0, height: 480.0, screenWidth: 320, screenHeight: 480

The dpi value is the number of pixels per inch on the screen. If you have a 160dpi screen, 1dp=1px. If I now have a 480* 800,160 dp screen, then the actual area is larger than the 480* 800,240 dp screen, but the resolution is not as good as the rear screen.

If some physical mobile phones find that the resolution is much smaller than the actual resolution during the test, the pixel value of dp unit is obtained here, which can be converted by the density value of dp, as follows:

480*800 cell phone (WVGA)density=240.

The conversion formula is as follows:


pixs =dips * (density/160)
dips=(pixs*160)/density

480 by 800 is px. And 320 times 533 is dp

5. Some applications of resources

* Different layout

The screen size of Android mobile phone is not 1, there are 480x320, 640x360, 800x480. How do you get App to automatically adapt to different screens? In fact, it is very simple. You just need to create different layout folders in the res directory, such as layout-640x360 and layout-800x480. All layout files will be written into ES95en.java after compilation, and the system will choose the appropriate layout for use according to the size of the screen.

* hdpi, mdpi, ldpi

In the previous version, there was only one drawable, while in version 2.1 there are three ES106en-mdpi, ES108en-ldpi and ES110en-hdpi. these three are mainly to support multi-resolution.

* Differences between drawable-hdpi, ES116en-ES117en and ES118en-ES119en:

drawable-hdpi store high-resolution images, such as WVGA (480x800),FWVGA (480x854)
drawable-mdpi contains medium resolution images such as HVGA (320x480)
drawable-ldpi contains low-resolution images, such as QVGA (240x320)

The system will go to these folders to find the corresponding picture according to the resolution of the machine. In order to be compatible with different screens of different platforms when developing the program, it is recommended to store different versions of images in different folders according to requirements.

* Screen direction

Landscape and portrait automatically switch

Two directories, ES147en-ES148en and ES149en-ES150en, can be set up in the res directory, in which two layout files, portrait and landscape, can be placed respectively. In this way, the system will automatically call the corresponding layout file when the screen direction changes, so as to avoid the problem that one layout file cannot meet the requirements of two screens.

* Disable automatic switching

Just add the android:screenOrientation attribute limit to the ES155en.xml file.
Android:screenOrientation="landscape" // is limited to landscape display on this page
Android:screenOrientation="portrait" // is to limit the number of pages displayed in portrait

* Font adaptive size

Method 1:

First, different font sizes are obtained according to different resolutions.

Create in RES

x320 values - 480 / strings xml set inside < dimen name="Text_size" > 30px < /dimen >
and
x400 values - 800 / strings xml set inside < dimen name="Text_size" > 40px < /dimen >
The font size is 30px and 40px at the resolution of 480X320 and 800X400 respectively.

This is called in the java file

int sizeOfText = (int) this.getResources().getDimension(R.dimen.Text_size);

Method 2:

Get the view width in onsizechanged of the view, 1 the default width is 320 in general, so calculate 1 zoom ratio rate = (float) w/320 w is the actual width

Then paint. setTextSize((int)(8*rate)) when setting font size; 8 is the font size that needs to be set when the resolution width is 320. The actual font size = the default font size x rate

I hope this article has been helpful in Android programming.


Related articles: