07/09/2018, 15:31

Viết tắt code trong android bằng cách dùng AndroidQuery

Xưa nay chúng ta quen với việc code android bằng những dòng code dài lê thê lết thết và nhìn rất khá là rối mắt (đối với ai mới bắt đầu sử dụng, tập tành code android) nay chúng ta có thể thực hiện viết code android ngắn gọn hơn bằng cách dùng thư viện Android Query. Bài viết này tôi chỉ chia sẻ ...

Xưa nay chúng ta quen với việc code android bằng những dòng code dài lê thê lết thết và nhìn rất khá là rối mắt (đối với ai mới bắt đầu sử dụng, tập tành code android) nay chúng ta có thể thực hiện viết code android ngắn gọn hơn bằng cách dùng thư viện Android Query.
Bài viết này tôi chỉ chia sẻ đôi chút về thư viện này, vì thư viện này cũng rất phổ biến rồi nên muốn chia sẻ lại cho cộng đồng thôi.

Ví dụ code android thường như sau

public void renderContent(Content content, View view) {
        ImageView tbView = (ImageView) view.findViewById(R.id.icon); 
        if(tbView != null){
                tbView.setImageBitmap(R.drawable.icon);
                tbView.setVisibility(View.VISIBLE);
                tbView.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                        someMethod(v);
                                }
                        });
        }
        
        TextView nameView = (TextView) view.findViewById(R.id.name);    
        if(nameView != null){
                nameView.setText(content.getPname());
        }
        
        TextView timeView = (TextView) view.findViewById(R.id.time);  
        
        if(timeView != null){
                long now = System.currentTimeMillis();
                timeView.setText(FormatUtility.relativeTime(now, content.getCreate()));
                timeView.setVisibility(View.VISIBLE);
        }
        
        TextView descView = (TextView) view.findViewById(R.id.desc);    
        
        if(descView != null){
                descView.setText(content.getDesc());
                descView.setVisibility(View.VISIBLE);
        }
}

sau khi dùng thư viện Android Query thì ta viết như sau:

public void renderContent(Content content, View view) {
        AQuery aq = new AQuery(view);
        aq.id(R.id.icon).image(R.drawable.icon).visible().clicked(this, "someMethod");  
        aq.id(R.id.name).text(content.getPname());
        aq.id(R.id.time).text(FormatUtility.relativeTime(System.currentTimeMillis(), content.getCreate())).visible();
        aq.id(R.id.desc).text(content.getDesc()).visible();      
}

Thật là quá ngắn gọn nhưng mà khó để hiểu cho những bạn mới bắt đầu, nhưng đối vái ai đó quen với việc viết tắt code thì nó giảm đi số lượng dòng code khá nhiều.

Bạn có thể tham khảo thêm tại https://code.google.com/p/android-query/ để biết thêm nhiều thứ hay ho hơn nữa.

Happy coding...

0