การทำ dynamic layout ในที่นี้ก็คือ การสร้าง pattern layout ขึ้นมาไฟล์เดียว(.xml ไฟล์เดียว) จากนั้นก็เรียกใช้ได้ตลอด ซึ่งมันก็จะมีรูปแบบเหมือนๆกัน แต่เนื้อหาข้างในต่างกัน ดังรูปครับ
1. ให้สร้าง pattern ไฟล์ .xml ขึ้นมาก่อนครับ ดังรูป
ก็ลากวางๆ เพื่อให้มันได้ form 1 form ขึ้นมานั่นแหล่ะครับ โค๊ดข้างในก็ไม่มีอะไรมาก ธรรมดาๆ เลยครับ ประมาณนี้ ชื่อไฟล์ว่า form_topic.xml เก็บไว้ในโฟลเดอร์ layout ครับ
2. เราต้องมีหน้าหลักที่จะเรียกใช้ form_topic.xml นั้นครับ หมายความว่า เราจะเอา form_topic.xml ไปยัดใส่ในหน้าหลักนั้นแบบวนลูปยัดตัวเดิม แล้วแก้ไขข้อมูลข้างในเอาครับ หน้าหลักจะเป็นหน้าว่างๆ ที่ไม่มีอะไรอยู่เลยครับ รูปหน้าหลักดังนี้ครับ
ตรงที่ให้จำคือตัวสำคัญเลยครับ เราจะใช้ LinearLayout นี้เป็นตัวอ้างอิงในการยัด form_topic.xml เข้าไปครับ
3. เขียน java ควบคุมเพื่อยัด form_topic.xml เข้าไป
อันนี้ผมเขียนเป็น method form เอาไว้น่ะครับ
private View formTopic(Topic topic){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.form_topic, null); //อ้างถึงไฟล์ layout นั้นครับ
new ImageLoader(((ImageView) view.findViewById(R.id.topic_image))).execute(topic.getImage());
((ImageView) view.findViewById(R.id.topic_image)).setOnClickListener(new ImageClick());
((TextView) view.findViewById(R.id.topic_username)).setText(topic.getName());
((TextView) view.findViewById(R.id.topic_text)).setText(topic.getContent());
((TextView) view.findViewById(R.id.topic_radius)).setText(topic.getRadius());
((TextView) view.findViewById(R.id.topic_nof_comment)).setText("comment(" + topic.getNumberOfComment()+")");
((TextView) view.findViewById(R.id.topic_nof_comment)).setOnClickListener(new CommentsClick());
if(topic.getUserId().equals(this.id) && !topic.getNotRead().equals("0")){
((TextView) view.findViewById(R.id.topic_readmore)).setText("+" + topic.getNotRead());
((TextView) view.findViewById(R.id.topic_readmore)).setTextColor(Color.RED);
}else{
((TextView) view.findViewById(R.id.topic_readmore)).setOnClickListener(new CommentsClick());
}
((TextView) view.findViewById(R.id.topic_time)).setText(topic.getTime());
String imageUserType;
if(topic.getUserType().equals("1")){
imageUserType = R.drawable.friends_marker;
}else {
imageUserType = R.drawable.other_marker;
}
if(topic.getUserId().equals(this.id)){
imageUserType = R.drawable.user_marker;
((ImageView) view.findViewById(R.id.topic_delete)).setVisibility(View.VISIBLE);
((ImageView) view.findViewById(R.id.topic_delete)).setOnClickListener(new RemoveClick());
}
((ImageView) view.findViewById(R.id.topic_usertype)).setImageDrawable(
this.getResources().getDrawable(imageUserType)
);
return view;
}
เรียกใช้ method formTopic//ที่ให้จำครับ
LinearLayout local_feed_area = (LinearLayout) findViewById(R.id.local_feed_area);
for(int i=0; i<topic.length; i++){
local_feed_area.addView(formTopic(topic[i]));
//จับยัดใน LinearLayout ที่ให้จำไว้ครับ
}
จะได้ดังรูปนี้เลยครับ






ไม่มีความคิดเห็น:
แสดงความคิดเห็น