Android: using fragments programmatically

前端 未结 2 936
被撕碎了的回忆
被撕碎了的回忆 2020-12-28 23:04

For some reasons I can\'t use xml layout files.

But I need to create a tablet android app.

I decided to use fragments.

I want to create the same layo

2条回答
  •  Happy的楠姐
    2020-12-28 23:50

    What you're missing is the LayoutInflator. See this example from an activity:

    private void createPolicyTable() {
    
        if (customerInfo.getPolicies() == null || customerInfo.getPolicies().isEmpty()) {
            Log.v(TAG, "no policies were found.");
            return;
        }
    
        LinearLayout policyTable = (LinearLayout)findViewById(R.id.manage_my_policy_policy_table);      
        LayoutInflater inflater = getLayoutInflater();
        for(int i = 0; i < customerInfo.getPolicies().size(); i++) {
            Policy policy = customerInfo.getPolicies().get(i);
    
            LinearLayout row = (LinearLayout)inflater.inflate(R.layout.policy_table_row, null);
    
            ImageView type = (ImageView)row.findViewById(R.id.policy_table_row_type);
    
            if (policy instanceof PersonalVehiclePolicy) {
                type.setImageResource(R.drawable.auto_policy);
            }
            else if (policy instanceof HomeownersPolicy) {
                type.setImageResource(R.drawable.home_policy);
            }
    
            ((TextView)row.findViewById(R.id.policy_table_row_policy_number)).setText(policy.getPolicyNumber());
            ((TextView)row.findViewById(R.id.policy_table_row_amount_due)).setText(policy.getAmountDue());
            ((TextView)row.findViewById(R.id.policy_table_row_due_date)).setText(policy.getDueDate());
    
            row.setOnClickListener(createPolicyDetailsOnClickListener(policy));
    
            policyTable.addView(row);
    
        }
    
    }
    

    and the layout that's being inflated:

    
    
    
        
            
                
    
                         
                
                
            
    
            
                
                
                
                
            
        
    
    
    
    

提交回复
热议问题