刚刚接触Android开发,最近自己在上手开发一个手机短信应用,由于是从头开始开发,首先还是得设计实现界面,初步效果如图:
程序代码如下
1.MainActivity.java
package com.example.mymessageproject;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView messageListView;
private ArrayList messageList = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageListView = (ListView)this.findViewById(R.id.listView1);
MessageListAdapter adapter = new MessageListAdapter(this);
adapter.init();
messageListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
2.适配器类MessageListAdapter.java
package com.example.mymessageproject;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MessageListAdapter extends BaseAdapter{
private LayoutInflater mInflater;
private Context mContext = null;
private ArrayList<String> aDataList = new ArrayList<String>();
public void init(){
for(int i=1;i<=10;i++){
aDataList.add("发件人"+i);
//return;
}
}
public MessageListAdapter(Context context) {
mContext = context;
mInflater = LayoutInflater.from(mContext);
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public int getCount() {
// TODO Auto-generated method stub
return aDataList.size();
}
public View getView(int position, View convertView,
android.view.ViewGroup parent) {
final ImageView indexImage;
final TextView titleText;
final TextView descText;
final TextView countText;
final TextView timeText;
if (convertView == null) {
// 和item_custom.xml脚本关联
convertView = mInflater.inflate(R.layout.list_item, null);
}
indexImage = (ImageView)convertView.findViewById(R.id.index_image);
titleText = (TextView)convertView.findViewById(R.id.titleTextView);
descText = (TextView)convertView.findViewById(R.id.descTextView);
countText = (TextView)convertView.findViewById(R.id.countTextView);
timeText = (TextView)convertView.findViewById(R.id.timeTextView);
String strText = aDataList.get(position);
// 设置item中4个TextView的文本
titleText.setText(strText);
descText.setText("消息