澳门皇冠金沙网站-澳门皇冠844网站

热门关键词: 澳门皇冠金沙网站,澳门皇冠844网站

深入了解view以及自定义控件,表格展示数据

相当完整的Android音乐播放器,直接上效果图及源代码,自己欣赏,具体不再解释了,可以说是一个很给力的Android音乐播放器。

参考文章: http://blog.csdn.net/guolin_blog/article/details/12921889 Android LayoutInflater原理分析,带你一步步深入了解View(一) Android自定义View的实现方法,带你一步步深入了解View(四)

有时候项目中可能会用到表格的形式来展示信息,这样会比较直观的看到数据,也会很清晰的坐到数据对比,之前有一个项目用到了,就来记录一下:

示例代码:

这里面总共有三种自定义控件:

首先就是布局,页面很简单:

/*
 * Copyright (C) 2009 Teleca Poland Sp. z o.o. <android@teleca.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

自绘控件、组合控件、继承控件

不知道我什么贴不出来,页面就是include一个表格的头部,然后ScrollView嵌套一个自定义的listview

package com.teleca.jamendo.widget;

 

include嵌入的就是表格的头部,嵌入之后可以固定他的长度,宽度,比较方便,在外部写可以设置大小,颜色和线条之类的,我写的这个只是3个textview 之间加了view,顶部以及底部添加线条。

import com.teleca.jamendo.api.Album;
import com.teleca.jamendo.R;

  1. 自绘控件

    1. package com.example.DefineView1;

上面还有一个自定义的listview,因为scrollview里面添加listview的时候,不是自定义的时候只显示一条,所以我们为了解决这个问题,就自定义一个listview。

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;

2.   

3.  import android.content.Context;


4.  import android.graphics.Canvas;


5.  import android.graphics.Color; 

6.  import android.graphics.Paint; 

7.  import android.graphics.Rect; 

8.  import android.util.AttributeSet;


9.  import android.view.View; 

10.  

11. /** 

12.  * Created by
    zhuxuekui on 2015/5/18. 

13.  */ 

14.  

15. /** 

16.  * 自定义组合控件之
    自绘控件 

17.  */ 

18. public class CounterView extends View implements View.OnClickListener {


19.  

20.     private Paint mPaint; 

21.     private Rect mBounds; 

22.     private int mCount; 

23.     public CounterView(Context context,
    AttributeSet attrs) { 

24.         super(context, attrs); 

25.         mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);


26.         mBounds = new Rect(); 

27.         setOnClickListener(this); 

28.  

29.     } 

30.  

31.     @Override 

32.     protected void onDraw(Canvas canvas) { 

33.         super.onDraw(canvas); 

34.         mPaint.setColor(Color.BLUE);


35.         canvas.drawRect(0, 0,
    getWidth(), getHeight(), mPaint); 

36.         mPaint.setColor(Color.YELLOW);


37.         mPaint.setTextSize(30);


38.         String text =
    String.valueOf(mCount); 

39.         mPaint.getTextBounds(text,0,text.length(),mBounds);//
    获取文字区域(其实是一个mBounds)的宽度与高度,然后回调。


40.         float textWidth = mBounds.width();


41.         float textHeight = mBounds.height();


42.         canvas.drawText(text,
    getWidth() / 2 - textWidth / 2, getHeight() / 2 

43.                   textHeight / 2,
    mPaint); //在画布上绘制文字


44.     } 

45.  

46.     @Override 

47.     public void onClick(View view) { 

48.           mCount  ; 

49.           invalidate(); //重绘 

50.     } 

51. } 

在CounterView中,我们先初始化一些数据,然后设置view的点击事件。然后调用onclick方法,这里面有invalidate方法,重绘命令。然后调用ondraw方法,开始进行视图的绘制。

 

![](https://images0.cnblogs.com/blog/591534/201505/190012578385146.png)

1.  package com.example.DefineView1;


2.   

3.  import android.app.Activity; 

4.  import android.os.Bundle; 

5.   

6.  public class MyActivity extends Activity { 

7.      /**


8.       * Called when the
    activity is first created. 

9.       */ 

10.     @Override 

11.     public void onCreate(Bundle
    savedInstanceState) { 

12.         super.onCreate(savedInstanceState);


13.         setContentView(R.layout.main);


14.     } 

15. } 

import android.content.Context;

import android.util.AttributeSet;

import android.widget.ListView;

/**

* 解决ScrollView中嵌套ListView,ListView只显示一行问题

*/

public class WListView extends ListView {

    public WListView(Context context) {

        super(context);

    }

    public WListView(Context context, AttributeSet attrs) {

        super(context, attrs);

    }

    public WListView(Context context, AttributeSet attrs, int defStyleAttr) {

        super(context, attrs, defStyleAttr);

    }

    @Override

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        //根据模式据算每个child的高度和宽度

        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);

        super.onMeasure(widthMeasureSpec, expandSpec);

    }

}

/**
 * Widget bar represenation of album, used with AlbumBarFlipper
 *
 * @author Lukasz Wisniewski
 */
public class AlbumBar extends LinearLayout {
 
 protected TextView mArtistTextView;
 protected TextView mAlbumTextView;
 protected TextView mDescriptionTextView;
 protected RemoteImageView mCoverImageView;

 

接下来就是Activity里面的代码设置,构建一个Bean类存放数据,再构建一个适配器加载存放的数据,放到listview里面,完美的加载数据并显示.Bean类就不贴出来了,下面是Activity和Adapter的具体代码:

 public AlbumBar(Context context, AttributeSet attrs) {
  super(context, attrs);
  init();
 }

 

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.os.Handler;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ImageView;

import android.widget.ListView;

import android.widget.TextView;

import android.widget.Toast;

import com.example.ztms_usb.Framgment.inter_face.KeyPath;

import com.example.ztmsandroid_USB.R;

import com.ztmsandroid.data.Data;

import com.ztmsandroid.utils.SharedPreferencesUtils;

import com.ztmsandroid.utils.ui.ProgressDialogEx;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import okhttp3.Call;

import okhttp3.Callback;

import okhttp3.OkHttpClient;

import okhttp3.Request;

import okhttp3.Response;

/**

* 数据

*/

public class Data_Table extends Activity {

    private String current_timestamp, username, key;

    private ProgressDialogEx progressDlgEx;

    private Handler mHandler = new Handler();

    private String sensor;

    private ListView tableListView;

    private List list;

    private String time, temp, hum, v, id;

    private TextView dayin, sensorr;

    private ImageView back;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.datatable);

        Intent intent = getIntent();

        sensor = intent.getStringExtra("sensor");

        id = intent.getStringExtra("id");

        progressDlgEx = new ProgressDialogEx(this, mHandler);

        sensorr = (TextView) this.findViewById(R.id.sensor);

        sensorr.setText("Sensor:" sensor);

        back = (ImageView) this.findViewById(R.id.back);

        back.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                finish();

            }

        });

        ViewGroup tableTitle = (ViewGroup) findViewById(R.id.table_title);

        tableListView = (ListView) findViewById(R.id.list);

        show();

    }

    /*获取运单号信息*/

    private void show() {

        // TODO Auto-generated method stub

        username = SharedPreferencesUtils.getString(Data_Table.this, "userName", "");// 获取用户名

        key = Data.getInstance().key;

        current_timestamp = Data.getInstance().current_timestamp;

        new Thread() {

            @Override

            public void run() {

                progressDlgEx.simpleModeShowHandleThread();

                OkHttpClient okHttpClient = new OkHttpClient();

                String format = String.format(KeyPath.Path.head KeyPath.Path.lastdatas, "c" sensor, username, key, current_timestamp);

                Request build1 = new Request.Builder().url(format).build();

                okHttpClient.newCall(build1).enqueue(new Callback() {

                    @Override

                    public void onFailure(Call call, IOException e) {

                    }

                    @Override

                    public void onResponse(Call call, Response response) throws IOException {

                        String string = response.body().string();

                        if (string != null) {

                            try {

                                final JSONArray jsonarray = new JSONArray(string);

                                list = new ArrayList();

                                mHandler.post(new Runnable() {

                                    @Override

                                    public void run() {

                                        for (int i = 0; i < jsonarray.length(); i ) {

                                            try {

                                                JSONObject jsonObject = jsonarray.getJSONObject(i);

                                                time = jsonObject.get("time").toString();

                                                temp = jsonObject.get("temp").toString();

                                                hum = jsonObject.get("hum").toString();

                                                v = jsonObject.get("v").toString();

                                                list.add(new bean(time, temp, hum, v));

                                            } catch (JSONException e) {

                                                e.printStackTrace();

                                            }

                                        }

                                        TableAdapter adapter = new TableAdapter(Data_Table.this, list);

                                        tableListView.setAdapter(adapter);

                                    }

                                });

                            } catch (JSONException e) {

                                e.printStackTrace();

                            } finally {

                                progressDlgEx.closeHandleThread();

                            }

                        }

                    }

                });

            }

        }.start();

    }

}

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.TextView;

import com.example.ztmsandroid_USB.R;

import java.util.List;

public class TableAdapter extends BaseAdapter {

    private List list;

    private LayoutInflater inflater;

    public TableAdapter(Context context, List list) {

        this.list = list;

        inflater = LayoutInflater.from(context);

    }

    @Override

    public int getCount() {

        int ret = 0;

        if (list != null) {

            ret = list.size();

        }

        return ret;

    }

    @Override

    public Object getItem(int position) {

        return list.get(position);

    }

    @Override

    public long getItemId(int position) {

        return position;

    }

    @Override

    public View getView(int position, View convertView, ViewGroup parent) {

        bean goods = (bean) this.getItem(position);

        ViewHolder viewHolder;

        if (convertView == null) {

            viewHolder = new ViewHolder();

            convertView = inflater.inflate(R.layout.list_item, null);

            viewHolder.goodId = (TextView) convertView.findViewById(R.id.text_id);

            viewHolder.goodName = (TextView) convertView.findViewById(R.id.text_goods_name);

            viewHolder.goodCodeBar = (TextView) convertView.findViewById(R.id.text_codeBar);

            viewHolder.goodNum = (TextView) convertView.findViewById(R.id.text_num);

            convertView.setTag(viewHolder);

        } else {

            viewHolder = (ViewHolder) convertView.getTag();

        }

        viewHolder.goodId.setText(goods.getTime());

        viewHolder.goodId.setTextSize(13);

        viewHolder.goodName.setText(goods.getTemp());

        viewHolder.goodName.setTextSize(13);

        viewHolder.goodCodeBar.setText(goods.getHum());

        viewHolder.goodCodeBar.setTextSize(13);

        viewHolder.goodNum.setText(goods.getV());

        viewHolder.goodNum.setTextSize(13);

        return convertView;

    }

    public static class ViewHolder {

        public TextView goodId;

        public TextView goodName;

        public TextView goodCodeBar;

        public TextView goodNum;

    }

}

 public AlbumBar(Context context) {
  super(context);
  init();
 }
 
 /**
  * Sharable code between constructors
  */
 private void init(){
  LayoutInflater.from(getContext()).inflate(R.layout.album_bar, this);
  
  mArtistTextView = (TextView)findViewById(R.id.ArtistTextView);
  mAlbumTextView = (TextView)findViewById(R.id.AlbumTextView);
  mCoverImageView = (RemoteImageView)findViewById(R.id.CoverImageView);
  //mCoverImageView.setDefaultImage(R.drawable.no_cd);
  mCoverImageView.setImageResource(R.drawable.no_cd);
  mDescriptionTextView = (TextView)findViewById(R.id.DescriptionTextView);
 }
 
 public void setAlbum(Album album){
  mArtistTextView.setText(album.getArtistName());
  mAlbumTextView.setText(album.getName());
  mCoverImageView.setDefaultImage(R.drawable.no_cd);
  mCoverImageView.setImageUrl(album.getImage());
 }
 
 public void setDescription(String description){
  mDescriptionTextView.setText(description);
 }
 
 public void setDescription(int resid){
  mDescriptionTextView.setText(resid);
 }

  1. 组合控件

适配器加载的Layout页面和主页面include的页面是同一个页面。Activity只需要把接口取到的数据add到list里面,然后放到适配器就好,然后适配器再展示数据,整体来说还是比较简单的,主要是最近两天比较空闲,所以就想着写点东西记录一下。

本文由澳门皇冠金沙网站发布于网络操作,转载请注明出处:深入了解view以及自定义控件,表格展示数据