簡體   English   中英

如何在現有布局(Android,JSON)中添加動態布局

[英]How to add dynamic layout in existing layout ( Android, JSON )

我有一個應用程序,其中顯示了來自JSON的數據。 我在相對布局的右側和左側的動態textview中顯示數據。 現在,我想將此布局添加到現有布局中,以便可以在OnClickListener上應用OnClickListener 現在,我將數據轉換為字符串,然后將該字符串設置為布局左側和右側的靜態文本視圖。

如何根據我從JSON獲得的數據數量動態生成textview?

 for (Region object : temp.phonelist.regionList)

            {
                if (object.getCCInfoShortDesc() != null ||  !(object.getCCInfoShortDesc().equals(null)))
                {
                    Log.i("nullexception", "nullexception");

                    holder.tvDescription.setText(object.getCCInfoShortDesc());
                    holder.tvDescription.setVisibility(View.VISIBLE);
                }else {
                    Log.i("nullexception1", "nullexception1");
                    holder.tvDescription.setVisibility(View.GONE);
                }


                leftContent += object.getCCInfoLeft() + ":" + "\n";
                rightContent += object.getCCInfoRight()  + "\n";

            }
            Log.i("lefftcontent", leftContent);
            Log.i("rightcontent", rightContent);

            if (leftContent != null) {
                holder.tvData2.setText(leftContent);
                holder.tvData2.setVisibility(View.VISIBLE);
            } 
            if (rightContent != null) {
                holder.tvData1.setText(rightContent);
                holder.tvData1.setVisibility(View.VISIBLE);
            } 
How it is possible to genrate textview dynamically 
on the basis of number of data i am getting from json.

每次在forloop上進行迭代時 ,都需要創建TextView並將其添加到parent layout 因此,您將擁有temp.phonelist.regionList每個元素的temp.phonelist.regionList

樣品:

 for (Region object : temp.phonelist.regionList)
 {
     TextView tx = new TextView(context); //creating a new instance if textview
     //yourstuff goes here
     tx.setText(text_you_want);
     yourView.addView(tx); //this is to add the textView on each iteration

 }

您可以通過這種方式來做。

  final int Count = < Number of TextViews>; // total number of textviews to add

   final TextView[] TextViewsARR = new TextView[N]; // create an empty array;

   for (int i = 0; i < Count; i++) {
   // create a new textview
   final TextView rowTextView = new TextView(this);

   // set some properties of rowTextView or something
   rowTextView.setText("This is row #" + i);

   // add the textview to the linearlayout
   myLinearLayout.addView(rowTextView);

  // save a reference to the textview for later
    TextViewsARR [i] = rowTextView;
  }
  • 我下面有一個示例,該示例可動態生成一個checkbox ,如果您觀察到我正在基於cursor count生成該checkbox 您可以根據自己的需要調整
  • 代替checkbox使用texview
  • 提供linearrelative等任何布局,並dynamically生成視圖

private CheckBox chkBoxMealType[] = null;

mCursor = db.rawQuery("SELECT meal_type_id,meal_type_name FROM meal_type_mas", null);

            if(mCursor.moveToFirst()){
                do{
                    if(chkBoxMealTypeCnt==0){
                        chkBoxMealType=new CheckBox[mCursor.getCount()];
                    }
                    //create a general view for checkbox
                    chkBoxMealType[chkBoxMealTypeCnt]= new CheckBox(getActivity());
                    //Create params for veg-checkbox
                    //Reason:: we don't need to worry about the data exist in cuisine_type_mas table
                    chkBoxMealType[chkBoxMealTypeCnt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
                    chkBoxMealType[chkBoxMealTypeCnt].setTextColor(getResources().getColor(R.color.searchGoldLight));
                    chkBoxMealType[chkBoxMealTypeCnt].setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
                    chkBoxMealType[chkBoxMealTypeCnt].setTag(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_ID)));
                    chkBoxMealType[chkBoxMealTypeCnt].setText(WordUtils.capitalizeFully(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_NAME))));
                    mealTypeContainer.addView(chkBoxMealType[chkBoxMealTypeCnt]);
                    //since cursor count starts from 0 last count must be allowed
                    chkBoxMealTypeCnt++;

                }while(mCursor.moveToNext());
                Log.d("", "");
            }

我還有另一個示例.....下載此項目(單擊此處)並在您的編輯器中運行

快照 ::

快照

首先,您需要在布局中添加一個View。就像您可以嘗試使用LinearLayout或Horizo​​ntalLayout一樣,然后將動態textview附加/添加到該布局。

務實的你可以這樣嘗試

packageButtons = new ArrayList<TextView>(); // Create your textview arraylist like this
        for(int a = 0; a < your_text_view_from_json.size(); a++){

               final TextView rowTextView;
               rowTextView = new TextView(getApplicationContext());
               rowTextView.setText(taxi_type_spin.get(a).taxi_type);
               rowTextView.setTextSize(15);
               rowTextView.setTextColor(getResources().getColor(R.color.white));
               LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0,
                       LinearLayout.LayoutParams.WRAP_CONTENT, 1);
               //rowTextView.setPadding(0, 0, 0, 0);      
               packageButtons.add(rowTextView);
               rowTextView.setLayoutParams(lparam);
               rowTextView.setId(a);
               final int b = a;
               // get value of clicked item over here .. 

               rowTextView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Button btn = (Button)v;
                    String get_value = btn.getText().toString();
                    //Toast.makeText(getApplicationContext(), "Button name is : " + get_value + " AND ID IS : " + rowTextView.getId(), Toast.LENGTH_LONG).show();
                    if(taxi_type_spin.get(b).taxi_type.equalsIgnoreCase(Utils.Hourly_Package))
                    {
                        setTaxiType(rowTextView.getId(),true);
                        ll_spin.setVisibility(View.VISIBLE);

                    }
                    else
                    {
                        setTaxiType(rowTextView.getId(),false);
                        ll_spin.setVisibility(View.GONE);
                    }
                    setSelectedButtonColor(b);

                }
            });

              // add the textview to the linearlayout
              myLinearLayout.addView(rowTextView);

注意 rowTextView ..這是附加到XML文件的默認視圖

希望能幫助到你!

private void setLayout(LinearLayout llayout,
        final ArrayList<String> items) {

    for (int i = 0; i < items.size(); i++) {
        LinearLayout row = null;
        LayoutInflater li = getLayoutInflater();
        row = (LinearLayout) li.inflate(R.layout.custom_item,
                null);

        ImageView image = (ImageView) row.findViewById(R.id.image);                 

        llayout.addView(row);
    }
}

我建議您使用ArrayList,因為類java.util.ArrayList提供了resizable-array,這意味着可以動態地從列表中添加和刪除項目。

並從ArrayList獲取值,如下所示:

for(int i=0; i<arrayList.size(); i++)
        {             
           textName.setText(object.getName());             
        } 

這是您這樣做的解決方案,采用一種布局(線性或相對)並動態添加控件。...

    LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    for (int i = 0; i < 4; i++)
    {

            TextView txtDemo = new TextView(getActivity());
            txtDemo .setTextSize(16);
            txtDemo .setLayoutParams(lp);
            txtDemo .setId(i);
            lp.setMargins(0, 10, 0, 0);
            txtDemo .setPadding(20, 10, 10, 10);
            txtDemo .setText("Text View"+ i);
            linearlayout.addView(txtDemo );

        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM