2013-03-06 1 views
1

선형 레이아웃에서 행을 동적으로 추가하려고하지만 xml을 만들고 응용 프로그램 충돌을 실행합니다. 내 XML과 소스 코드 아래에. 내 XML 코드 ::안드로이드의 Scrollview에서 동적 행보기를 추가하는 방법?

<?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

+0

내 json 파일의 DbAdpter 파일에서 jshon의 URL을 가져옵니다. – crickpatel0024

+0

안녕 Droider 내 DBadpter 코드를 넣어주세요 그것을 참조하십시오. – crickpatel0024

답변

1

당신은 LinearLayoutLayoutParam 아이에게보기를 추가 할 때 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

안녕하세요, 답장을 보내 주셔서 감사합니다.하지만 모든 항목을 행에 이미지를 넣고 코드 뷰를 표시하지 않으려면 내 xml 코드를 확인하십시오. 내 코드가 잘못되었습니다. – crickpatel0024

+0

예외가 있습니까? –

+0

오류가 발생하지 않지만 activity.only의 이미지보기에는 표시되지 않습니다. 상단 선형 레이아웃보기를 참조하십시오. – crickpatel0024

0

내가 너무 빨리 당신이 원하는 행에 대한 별도의 XML 파일을 만든 다음 해당 뷰를 팽창 및 레이아웃에 동적으로 추가하는 것입니다 필요 이전 대답을 게시 죄송합니다

같은 이

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

이 레이아웃을 선형 레이아웃에 추가하십시오.

row_xml 파일이

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

</LinearLayout> 
+0

Thanks Ashish For 내가 당신의 코드를 답장! – crickpatel0024

+0

Ashish 내가 동적으로 이미지보기 및 진행률 막대 및 단추를 추가하려면 및 linearlayout있는 scrollview 추가하고 목록보기 만 scrollview .how 추가하는 데 사용되지 않습니다. – crickpatel0024

+0

listview와 마찬가지로 행에 대한 xml 뷰를 만든 다음이를 선형 레이아웃에 부 풀면 내가 게시 한 코드를 사용할 수 있습니다.이 생성 된 레이아웃을 자신의 선형 레이아웃에 추가하면 getView 메소드의 listview 행을 수정하는 것처럼 수정할 수 있습니다 –

관련 문제