2014-06-06 6 views
0

나는 웹 페이지에서 제품 목록을 얻는 함수를 가지고 있으며 목록의 각 요소에 대해 tableLayout에 행을 추가하려고합니다. 내 레이아웃 XML 파일에안드로이드에서 tableLayout에 행을 동적으로 추가하는 방법

public void getProductsOfCategory() throws IOException{ 
     new Thread(){ 
      public void run(){ 
       //background code... 
       try { 
        Bundle extras = getIntent().getExtras(); 
        String categoryName = extras.getString("categoryName"); 

        HttpGet httpget = new HttpGet("http://romal.hopto.org/foodadvisor/users/getProductsOfCategory.json?category="+categoryName); 
        HttpResponse httpresp = httpClient.execute(httpget); 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        httpresp.getEntity().writeTo(baos); 
        final String content = new String(baos.toByteArray()); 
        CategoryActivity.this.runOnUiThread(new Runnable(){ 
         public void run(){ 
          //foreground code (UI) 
          //update user interface, for example, showing messages 
          try { 
           JSONObject jObject = new JSONObject(content); 
           JSONArray productsList = jObject.getJSONArray("response"); 
           for(int i=0; i<productsList.length();i++){ 
            JSONObject product = productsList.getJSONObject(i); 
            JSONObject productData = product.getJSONObject("Product"); 
            String productDescription = productData.getString("description"); 
           } 
          } catch (JSONException e) { 
           // TODO Auto-generated catch block 
           e.printStackTrace(); 
          } 
         } 
        }); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     }.start(); 
    } 

나는 다음과 같은 테이블 레이아웃을 정의했습니다 :

<TableLayout 
      android:id="@+id/tableOfProducts" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" > 

      <TextView 
       android:id="@+id/productDescription" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="TextView" 
       android:paddingBottom="7dp" 
       android:paddingLeft="14dp" 
       android:paddingRight="14dp" 
       android:paddingTop="7dp" 
       android:textSize="20dp" /> 

     </TableLayout> 

가 내가 새 행과 새로운 텍스트 뷰를 추가, 루프에 대한 일부 추가 코드를 추가 할 필요가 상상 제품의 설명이있는. 자열로 텍스트보기의 내용을 설정하십시오. 어떻게해야합니까? 이것에 대한

답변

8

이 부분을 확인하십시오. 테이블 행을 동적으로 생성하는 일반적인 방법입니다.그것을 수정 따라

XML 파일

<TableLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 

android:id="@+id/main_table" 
android:layout_height="wrap_content" 
android:layout_width="match_parent"> 
</TableLayout> 

자바 PART

TableLayout t1; 

TableLayout tl = (TableLayout) findViewById(R.id.main_table); 

열 머리글을 잡고 테이블 행 헤더를 작성

TableRow tr_head = new TableRow(this); 
tr_head.setId(10); 
tr_head.setBackgroundColor(Color.GRAY);  // part1 
tr_head.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, 
LayoutParams.WRAP_CONTENT)); 

나는 테이블에 열을 추가 한 후 테이블 행

TextView label_hello = new TextView(this); 
     label_hello.setId(20); 
     label_hello.setText("HELLO"); 
     label_hello.setTextColor(Color.WHITE);   // part2 
     label_hello.setPadding(5, 5, 5, 5); 
     tr_head.addView(label_hello);// add the column to the table row here 

     TextView label_android = new TextView(this); // part3 
     label_android.setId(21);// define id that must be unique 
     label_android.setText("ANDROID..!!"); // set the text for the header 
     label_android.setTextColor(Color.WHITE); // set the color 
     label_android.setPadding(5, 5, 5, 5); // set the padding (if required) 
     tr_head.addView(label_android); // add the column to the table row here 

에 두 개의 데이터 섹션을 추가 해요 테이블이 우리가 시작에서 페치 기본 테이블 레이아웃을 행 추가하기 위해 시간을 행

tl.addView(tr_head, new TableLayout.LayoutParams(
       LayoutParams.FILL_PARENT,     //part4 
       LayoutParams.MATCH_CONTENT));  

편집 : 당신은 당신의 코드에서 다음과 같은 작업을 수행 할 수

TextView[] textArray = new TextView[productsList.length()]; 
TableRow[] tr_head = new TableRow[productsList.length()]; 

for(int i=0; i<productsList.length();i++){ 
JSONObject product = productsList.getJSONObject(i); 
JSONObject productData = product.getJSONObject("Product"); 
String productDescription = productData.getString("description"); 

//Create the tablerows 
tr_head[i] = new TableRow(this); 
tr_head[i].setId(i+1); 
tr_head[i].setBackgroundColor(Color.GRAY); 
tr_head[i].setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, 
LayoutParams.WRAP_CONTENT)); 

// Here create the TextView dynamically 

textArray[i] = new TextView(this); 
     textArray[i].setId(i+111); 
     textArray[i].setText(productDescription); 
     textArray[i].setTextColor(Color.WHITE); 
     textArray[i].setPadding(5, 5, 5, 5); 
     tr_head[i].addView(textArray[i]); 

//은 텍스트 뷰와 TableRow 배열이 필요하지 않습니다 만들기 테이블 레이아웃

tl.addView(tr_head[i], new TableLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, 
        LayoutParams.WRAP_CONTENT)); 

} // end of for loop 

각 테이블 행을 추가합니다. part1, part2, part3 (필드가 두 개 이상 필요한 경우) 및 part4을 for 루프 내에 포함 할 수 있습니다.

+1

@JuanPedroMartinez 누구나 이해할 수 있도록 영어로 의견을 말하십시오. – Aniruddha

+0

그는 당신이 훌륭한 일을했다고 말합니다. 그러나, 그것은 나에게 오류를주고, 나는 그것을 해결하는 방법을 모른다. :) – Julia

+0

오케이, 무엇이 오류입니까? – Aniruddha

0

, 당신은 다음, 그 다음 루프에서

<ScrollView> 
    <LinearLayout orientation=vertical id="+id/rowHolder"> 
    </LinearLayout 
</scrollview> 

처럼 layout.xml 파일을 수정 행 레이아웃을 팽창하고 rowHolder에 런타임 추가해야 행에 대해 하나 개의 XML 파일을 생성해야 목적.

첫째, 인플레이터 :

1

봐, 난 당신이 당신의 tableview에 행을 추가로 XML을 수정해야 할 생각

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 



//Here you can set up the layoutparameters from your tableview and the rowview. 
//Maybe you don't have to modify nothing from the parameters of your tableview so 
//you can dismiss it. 

TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT); 
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); 

//Here were we take the tablelayout from your xml 
TableLayout tableLayout = (TableLayout)inflater.inflate(R.layout.tableOfProducts, null); 

//Like a told you before, maybe you don't need set the parameters of the tablelayout 
//so you can comment next line. 
tableLayout.setLayoutParams(this.tableParams); 

TableRow tableRow = new TableRow(context); 
tableRow.setLayoutParams(this.tableParams); 

//Here you have to create and modify the new textview. 
TextView textView = new TextView(context); 
textView.setLayoutParams(this.rowParams); 

tableRow.addView(textView); 

tableLayout.addView(tableRow); 

경우 :

LayoutInflater inflater = mContext.getLayoutInflater(); 

또는 이러한 방법으로

도움이된다면 더 많은 도움이 필요하다고 말해주세요! ;) Un saludo Gallega! 그대와 그대의 동료들 :

+0

내 함수가 다음 줄에서 실행 가능하기 때문에 문제가 발생합니다. LayoutInflater inflater = (LayoutInflater) this.getSystemService (Context.LAYOUT_INFLATER_SERVICE); 왜 그런지 짐작하니? Muchas gracias;) – Julia

+0

for LayoutInflater inflater = (LayoutInflater) this.getSystemService (Context.LAYOUT_INFLATER_SERVICE), "this"대신 yourActivityName.this를 사용하십시오. –

+0

Pankaj가 마지막 질문에 도움을 줬나요? 그렇지 않다면 내가 생각하는 다른 해결책이 있습니다. –