findViewByIdを一度だけ実行する。
setTagを使用する。
******************** MainActivity.java ********************
package jp.lesson.studyandroid;
import java.util.ArrayList;
import android.os.Bundle;
import android.view.LayoutInflater;import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.app.ListActivity;
import android.content.Context;
public class MainActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ValueItem data1 = new ValueItem();
data1.setMsg("Sample data0");
ValueItem data2 = new ValueItem();
data2.setMsg("Sample data1");
ValueItem data3 = new ValueItem();
data3.setMsg("Sample data2");
ArrayList<ValueItem> list = new ArrayList<ValueItem>();
list.add(data1);
list.add(data2);
list.add(data3);
ListAdapter adapter = new ValueItemAdapter(getApplicationContext(),list);
setListAdapter(adapter);
}
public class ValueItemAdapter extends ArrayAdapter<ValueItem> {
Context context;
LayoutInflater inflater;
public ValueItemAdapter(Context context, ArrayList<ValueItem> objects) {
super(context, 0, objects);this.context = context;
this.inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {ValueItem item = (ValueItem)getItem(position);
ViewHolder holder =null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.chkbox = (CheckBox)convertView.findViewById(R.id.checkBox1);
holder.txtview = (TextView)convertView.findViewById(R.id.textView1);
holder.button = (Button)convertView.findViewById(R.id.button1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder)convertView.getTag();
}
holder.chkbox.setChecked(item.isChecked());
holder.txtview.setText(item.getTextmsg());
return convertView;
}}
static class ViewHolder {
CheckBox chkbox;
TextView txtview;
Button button;
}
}
package jp.lesson.studyandroid;
public class ValueItem {
private String strmsg = "";public boolean isChecked() {
return true;
}
public CharSequence getTextmsg() {
return strmsg;}
public void setMsg(String string) {
this.strmsg = string;}
}
******************** activity_main.java ********************
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/android:list"android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="@+id/android:empty"android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="empty" />
</LinearLayout>
0 件のコメント:
コメントを投稿