2013-03-06 110 views
1

我想在線性佈局中動態添加行,但我創建了xml,並且運行應用程序崩潰。我的xml和源代碼如下。 我的XML代碼::如何在Android中的滾動視圖中添加動態行視圖?

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <LinearLayout 
     android:id="@+id/main_lay" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal" 
     android:background="#437654" > 

     <Button 
      android:id="@+id/all_btn" 
      android:layout_width="100dip" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="BACk" /> 

     <TextView 
      android:id="@+id/accepted_all" 
      android:layout_width="100dip" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="DownLoad Video" /> 

     <Button 
      android:id="@+id/not_shown" 
      android:layout_width="100dip" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="All DOwnload" /> 
    </LinearLayout> 

    <ScrollView 
     android:id="@+id/ScrollView01" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical" > 


    </ScrollView> 

</LinearLayout> 

我custom_row.xml代碼下面::

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:descendantFocusability="blocksDescendants" 
    android:orientation="horizontal" 
    android:id="@+id/linearchild"> 

    <ImageView 
     android:id="@+id/ColImgPath" 
     android:layout_width="50dp" 
     android:layout_height="50dp" /> 

    <TableLayout 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical" > 

     <TableRow 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dip" > 

      <TextView 
       android:id="@+id/ColStatus" 
       android:text="Status" 
       android:textAppearance="?android:attr/textAppearanceSmall" /> 

      <ProgressBar 
       android:id="@+id/progressBar" 
       style="?android:attr/progressBarStyleHorizontal" 
       android:layout_width="100dp" 
       android:layout_height="wrap_content" /> 
     </TableRow> 

     <TableRow 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dip" > 

      <Button 
       android:id="@+id/btnDownload" 
       style="?android:attr/buttonStyleSmall" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Download" /> 

      <Button 
       android:id="@+id/btnView" 
       style="?android:attr/buttonStyleSmall" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Delete" /> 
     </TableRow> 
    </TableLayout> 

</LinearLayout> 

和我的新編輯源代碼::

 public class TestDynamicScroll extends Activity { 
    ArrayList<Url_Dto> list = new ArrayList<Url_Dto>(); 
    ScrollView slnLay; 
    TableLayout download_table; 
    File download; 
    public static final int DIALOG_DOWNLOAD_THUMBNAIL_PROGRESS = 0; 
    String strDownloaDuRL; 
    ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>(); 
    TableRow row, row1, row2; 
    ImageView im; 
    ProgressBar pr; 
    TextView tv; 
    Button dl; 
    Button cl; 
    private Context mContext; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_test_dynamic_scroll); 

     list = DBAdapter.getUrl_Detail(); 
     fillCountryTable(); 
    } 

    void fillCountryTable() { 
     mContext =TestDynamicScroll.this; 
     LinearLayout childln = null ; 

     slnLay = (ScrollView) findViewById(R.id.scrollView1); 
     LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View convertView = inflater.inflate(R.layout.custom_row, null); 


     for (int current = 0; current < list.size(); current++) { 

      Log.v("log_tag", "Current ::: " + current); 
      childln = (LinearLayout) convertView.findViewById(R.id.linearchild); 
      im = new ImageView(this); 
      im = (ImageView) convertView.findViewById(R.id.ColImgPath); 
      im.setImageResource(Url_Dto.images[current]); 

      childln.addView(im); 

      tv = new TextView(this); 
      tv = (TextView) convertView.findViewById(R.id.ColStatus); 
      tv.setText("..."); 

      childln.addView(tv); 

      pr = new ProgressBar(this); 
      pr = (ProgressBar) convertView.findViewById(R.id.progressBar); 

      childln.addView(pr); 

      dl = new Button(this); 
      dl = (Button) convertView.findViewById(R.id.btnDownload); 

      childln.addView(dl); 

      cl = new Button(this); 
      cl = (Button) convertView.findViewById(R.id.btnView); 


      childln.addView(cl); 


      dl.setOnClickListener(new View.OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        dl.setEnabled(false); 
        dl.setTextColor(Color.GRAY); 

        //startDownload(dl.getId()); 
       } 
      }); 

     } 
     slnLay.addView(childln); 




    } 

    public void startDownload(final int position) { 

     Runnable runnable = new Runnable() { 
      int Status = 0; 

      public void run() { 

       // String urlDownload = list.get(position).url_video; 
       String urlDownload = list.get(position).url_video; 
       Log.v("log_tag", "urlDownload ::: " + urlDownload); 

       int count = 0; 
       try { 

        URL url = new URL(urlDownload); 
        URLConnection conexion = url.openConnection(); 
        conexion.connect(); 

        int lenghtOfFile = conexion.getContentLength(); 
        Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); 

        InputStream input = new BufferedInputStream(
          url.openStream()); 

        // Get File Name from URL 
        String fileName = urlDownload.substring(
          urlDownload.lastIndexOf('/') + 1, 
          urlDownload.length()); 
        download = new File(
          Environment.getExternalStorageDirectory() 
            + "/download/"); 
        if (!download.exists()) { 
         download.mkdir(); 
        } 
        strDownloaDuRL = download + "/" + fileName; 
        OutputStream output = new FileOutputStream(strDownloaDuRL); 

        byte data[] = new byte[1024]; 
        long total = 0; 

        while ((count = input.read(data)) != -1) { 
         total += count; 
         Status = (int) ((total * 100)/lenghtOfFile); 
         output.write(data, 0, count); 



         TestDynamicScroll.this.runOnUiThread(new Runnable() { 
          public void run() { 
           // updateStatus(position, Status); 

          } 
         }); 

        } 

        output.flush(); 
        output.close(); 
        input.close(); 

       } catch (Exception e) { 
       } 

      } 
     }; 
     new Thread(runnable).start(); 
    } 

} 

MY DbAdpter類在下面:: :

public class DBAdapter { 
    public static String url = "http://imprintingdesign.com/hiren_testing/TestHopeNew/testHope/data/url.json"; 


    public static ArrayList<Url_Dto> getUrl_Detail() { 

     ArrayList<Url_Dto> fetchUrl_Detail = new ArrayList<Url_Dto>(); 
     String result = ""; 
     InputStream is = null; 

     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

     // http post 
     try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(url); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
     } catch (Exception e) { 
      Log.e("log_tag", "Error in http connection " + e.toString()); 
     } 
     // convert response to string 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      result = sb.toString(); 
     } catch (Exception e) { 
      Log.e("log_tag", "Error converting result " + e.toString()); 
     } 

     // parse json data 
     try { 
      JSONObject json_obj = new JSONObject(result); 
      JSONArray j_Arr_fn = json_obj.getJSONArray("children"); 

      for (int i = 0; i < j_Arr_fn.length(); i++) { 
       JSONObject json_objs = j_Arr_fn.getJSONObject(i); 
       Url_Dto proDto = new Url_Dto(); 
       proDto.url_video= json_objs.getString("videoUrl"); 
       Log.v("log_tag","Url :::"+ json_objs.getString("videoUrl")); 
       fetchUrl_Detail.add(proDto); 
       } 

     } catch (JSONException e) { 
      Log.e("log_tag", "Error parsing data " + e.toString()); 
     } 
     return fetchUrl_Detail; 

    } 

我要像佈局顯示如下:

enter image description here

我的錯誤得到它:::

03-14 13:31:39.453: E/AndroidRuntime(770): FATAL EXCEPTION: main 
03-14 13:31:39.453: E/AndroidRuntime(770): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testdyanamicscroll/com.example.testdyanamicscroll.TestDynamicScroll}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.os.Handler.dispatchMessage(Handler.java:99) 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.os.Looper.loop(Looper.java:130) 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.app.ActivityThread.main(ActivityThread.java:3683) 
03-14 13:31:39.453: E/AndroidRuntime(770): at java.lang.reflect.Method.invokeNative(Native Method) 
03-14 13:31:39.453: E/AndroidRuntime(770): at java.lang.reflect.Method.invoke(Method.java:507) 
03-14 13:31:39.453: E/AndroidRuntime(770): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 
03-14 13:31:39.453: E/AndroidRuntime(770): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 
03-14 13:31:39.453: E/AndroidRuntime(770): at dalvik.system.NativeStart.main(Native Method) 
03-14 13:31:39.453: E/AndroidRuntime(770): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.view.ViewGroup.addViewInner(ViewGroup.java:1976) 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.view.ViewGroup.addView(ViewGroup.java:1871) 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.view.ViewGroup.addView(ViewGroup.java:1828) 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.view.ViewGroup.addView(ViewGroup.java:1808) 
03-14 13:31:39.453: E/AndroidRuntime(770): at com.example.testdyanamicscroll.TestDynamicScroll.fillCountryTable(TestDynamicScroll.java:76) 
03-14 13:31:39.453: E/AndroidRuntime(770): at com.example.testdyanamicscroll.TestDynamicScroll.onCreate(TestDynamicScroll.java:55) 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 
03-14 13:31:39.453: E/AndroidRuntime(770): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 
03-14 13:31:39.453: E/AndroidRuntime(770): ... 11 more 
+0

什麼是將對DBAdapter? – Calvin 2013-03-12 12:23:32

+0

DbAdpter在我的JSON文件我得到的URL從jshon。 – crickpatel0024 2013-03-12 12:34:12

+0

嗨Droider我把我的DBadpter代碼請看看它。 – crickpatel0024 2013-03-12 12:35:59

回答

1

你需要添加LayoutParam兒童鑑於LinearLayout時使用的LinearLayout.LayoutParam對象。 。

更改下面的代碼

for(int i=0;i<list.size();i++){ 

      im[i] = new ImageView(TestDynamicScroll.this); 

      im[i].setLayoutParams(new LayoutParams(50, 50)); 

      im[i].setImageResource(list.get(i).images[i]); 
      slnLay.addView(im[i]); 

     } 

for(int i=0;i<list.size();i++){ 

     im[i] = new ImageView(TestDynamicScroll.this); 

     im[i].setLayoutParams(new LinearLayout.LayoutParams(50, 50)); 

     im[i].setImageResource(list.get(i).images[i]); 
     slnLay.addView(im[i]); 

    } 
+0

嗨praple感謝您的回覆,但我希望我把圖像放在行中的所有項目,我把你的代碼imageview不顯示在我的視圖中請檢查我的xml代碼在我的代碼中有什麼問題請幫助我! – crickpatel0024 2013-03-06 07:12:02

+0

是你的例外了嗎? – 2013-03-06 07:13:28

+0

沒有任何錯誤得到,但不顯示在活動圖像視圖。只能看到頂部線性佈局顯示。 – crickpatel0024 2013-03-06 07:14:54

0

對不起,我貼在前面的回答有點太快了,你需要做的是創造你想要一個排一個單獨的XML文件,然後膨脹這一觀點,並動態地添加到您的佈局

像這

private LinearLayout mInputView; 
    mInputView = (LinearLayout) getLayoutInflater().inflate(R.layout.row_xml, null); 
    ImageView newImage=(ImageView)mInputView.findViewbyId(R.id.imageid); 

並將此充氣佈局添加到您的linearlayout。

的row_xml文件可能具有的結構是這樣

<LinearLayout> 
<ImageView/> 
<ProgressBar/> 
<ImageView/> 

</LinearLayout> 
+0

Thanks Ashish For回覆我試試你的代碼! – crickpatel0024 2013-03-06 07:24:11

+0

Ashish我想要動態添加圖像視圖和進度條和按鈕。並且在linearlayout中添加scrollview,並且我沒有使用listview只有scrollview。如何添加它。 – crickpatel0024 2013-03-06 07:36:34

+0

爲行創建一個xml視圖,就像使用listview做的那樣,然後將它膨脹爲linearlayout,您可以使用我爲此發佈的代碼。只需將此創建的佈局添加到您自己的線性佈局中即可修改它,就像修改getView方法中的listview行一樣 – 2013-03-06 07:41:29