1. 程式人生 > >android tablelayout動態實時新增資料

android tablelayout動態實時新增資料

//MainActivity.java

package
com.example.dell.app_test; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TableLayout; import android.widget.TableRow;
import android.widget.TextView; import java.security.spec.ECField; public class MainActivity extends AppCompatActivity { private Button btn1; private TableLayout tableLayout1; private Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super
.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
     //設定表頭 tableLayout1
=findViewById(R.id.tablelayout1); tableLayout1.setStretchAllColumns(true); TableRow row = new TableRow(getApplicationContext()); TextView number= new TextView(getApplicationContext()); TextView name
= new TextView(getApplicationContext()); TextView phone = new TextView(getApplicationContext()); number.setText("編號"); row.addView(number); name.setText("名稱"); row.addView(name); phone.setText("電話"); row.addView(phone); tableLayout1.addView(row);      
     //要想在介面中實現資料新增後重新整理,新增資料的程式碼要在Handler()函式中寫。 mHandler
=new Handler(){ @Override public void handleMessage(Message msg){ TableRow row = new TableRow(getApplicationContext()); TextView text= new TextView(getApplicationContext()); TextView text1 = new TextView(getApplicationContext()); text.setText("sssssf"); row.addView(text); text1.setText("ererere"); row.addView(text1); tableLayout1.addView(row); } }; btn1=(Button)findViewById(R.id.btn1); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { //建立執行緒,每隔一秒向介面中傳送一條資料 @Override public void run() { for(int i =0;i<10;i++){ try{ Thread.sleep(1000); mHandler.sendEmptyMessage(1); }catch (Exception e){ } } } }).start(); } }); } }
 
 
<!--activity_main.xml 只用新增一個TableLayout控制元件即可,Button控制元件是用來測試-->


<
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#dddddd" android:orientation="vertical"> <Button android:id="@+id/btn1" android:layout_width="100dp" android:layout_height="40dp" android:text="號"/> <TableLayout android:id="@+id/tablelayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> </TableLayout> </LinearLayout>