如何在Android中的Scrollview中添加动态行视图?

时间:2013-03-06 07:00:41

标签: android dynamic view scrollview programmatically-created

我想在线性布局中动态添加行但是我创建了xml并且我运行应用程序崩溃。我的xml和源代码如下。 我的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" >

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

中的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();
    }

}

我的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

我的错误Get It :::

 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

2 个答案:

答案 0 :(得分: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]);

    }

答案 1 :(得分: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>