-1

exmaple.here を解析する 1 つの xml を開発しました。展開可能な listview を使用する必要があります。しかし、これを開発することはできません。

これはコードです:

 public class CustomExpandableListExampleActivity extends ExpandableListActivity {

ExpandableListAdapter mAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set up our adapter
    mAdapter = new MyExpandableListAdapter();
    setListAdapter(mAdapter);
    registerForContextMenu(getExpandableListView());
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    menu.setHeaderTitle("Sample menu");
    menu.add(0, 0, 0, "Sample action");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();

    String title = ((TextView) info.targetView).getText().toString();

    int type = ExpandableListView.getPackedPositionType(info.packedPosition);
    if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
        int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
        int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
        Toast.makeText(this, title + ": Child " + childPos + " clicked in group " + groupPos,
                Toast.LENGTH_SHORT).show();
        return true;
    } else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
        int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
        Toast.makeText(this, title + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();
        return true;
    }

    return false;
}

public class MyExpandableListAdapter extends BaseExpandableListAdapter {
    // Sample data set.  children[i] contains the children (String[]) for groups[i].
    private String[] groups = { "Order Info", "Customer Info" };
    private String[][] children = {
            { "abc", "xyz", "ash", "anu" },
            { "SSE", "TJ", "PM", "SE" },

    };

    public Object getChild(int groupPosition, int childPosition) {
        return children[groupPosition][childPosition];
    }

    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    public int getChildrenCount(int groupPosition) {
        return children[groupPosition].length;
    }

    public TextView getGenericView() {
        // Layout parameters for the ExpandableListView
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 64);

        TextView textView = new TextView(CustomExpandableListExampleActivity.this);
        textView.setLayoutParams(lp);
        // Center the text vertically
        textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
        // Set the text starting position
        textView.setPadding(36, 0, 0, 0);
        return textView;
    }

    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
            View convertView, ViewGroup parent) {
        TextView textView = getGenericView();
        textView.setText(getChild(groupPosition, childPosition).toString());
        return textView;
    }

    public Object getGroup(int groupPosition) {
        return groups[groupPosition];
    }

    public int getGroupCount() {
        return groups.length;
    }

    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
            ViewGroup parent) {
        TextView textView = getGenericView();
        textView.setText(getGroup(groupPosition).toString());
        return textView;
    }

    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    public boolean hasStableIds() {
        return true;
    }

  }
 }

ここで、上記のコードには orderinfomation に子 (abc、xyz、ash、anu) の項目があります。自分。

public class SingleMenuItemActivity  extends Activity {

// XML node keys
static final String KEY_ARTIST = "payment_method";
static final String KEY_SUBTOTAL = "subtotal";
static final String KEY_DISCOUNT = "discount";
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_list_item);

    // getting intent data
    Intent in = getIntent();

    // Get XML values from previous intent
    String subtotal = in.getStringExtra(KEY_SUBTOTAL);
    String discount = in.getStringExtra(KEY_DISCOUNT);
    String payment_method = in.getStringExtra(KEY_ARTIST);
    TextView lblSub = (TextView) findViewById(R.id.subtotal_label);

    TextView lblPayment = (TextView) findViewById(R.id.payment_label);
    TextView lbldiscount = (TextView) findViewById(R.id.discount_label);
    lblSub.setText(subtotal);
    lbldiscount.setText(discount);
    lblPayment.setText(payment_method);
     }
       } 
4

2 に答える 2

1

ここでは、ExpandableListView を使用して xml ファイルを作成し、アクティビティの参照を取得します。以下のようなアダプターを作成します。アクティビティから、次のように項目を設定します。

           Map<String, List<CommonTask>> map = new HashMap<String, List<CommonTask>>();

    List<CommonTask> childItem1 = new ArrayList<CommonTask>();
    childItem1.add(new CommonTask("Child 1"));


    List<CommonTask> childItem2 = new ArrayList<CommonTask>();
         childItem2.add(new CommonTask("Child 2"));

            map.put("Parent 1", childItem1);
    map.put("Parent 2", childItem2);

          // Set on listview ExpandableListView reference

           expandListView.setAdapter(adapter);

public class ExpandableListViewAdapter extends BaseExpandableListAdapter {

private static final class ViewHolder {
    TextView textLabel;
    TextView groupTextLabel;

}

private final Map.Entry<Object, List<Object>> entries[];

private final LayoutInflater inflater;


public ExpandableListViewAdapter(final Context theContext,
        final Map<String, List<CommonTask>> map) {
    inflater = LayoutInflater.from(theContext);

    entries = map.entrySet().toArray(new Map.Entry[0]);

}

@Override
public Object getChild(final int groupPosition, final int childPosition) {
    final List<Object> childList = entries[groupPosition].getValue();

    return childList.get(childPosition);
}

@Override
public long getChildId(final int groupPosition, final int childPosition) {
    return childPosition;
}

@Override
public int getChildrenCount(final int groupPosition) {

    final List<Object> childList = entries[groupPosition].getValue();

    final int childCount = childList.size();

    return childCount;
}

@Override
public View getChildView(final int groupPosition, final int childPosition,
        final boolean isLastChild, final View theConvertView,
        final ViewGroup parent) {
    View resultView = theConvertView;

    ViewHolder holder = null;

    if (resultView == null) {
        resultView = inflater.inflate(R.layout.child_layout, null);

        holder = new ViewHolder();

        holder.textLabel = (TextView) resultView.findViewById(R.id.title);

        resultView.setTag(holder);
    } else {
        holder = (ViewHolder) resultView.getTag();
    }

    final Object item = getChild(groupPosition, childPosition);
    CommonTask commonTask = (CommonTask) item;
    holder.textLabel.setText(commonTask.getName());

    return resultView;
}

@Override
public Object getGroup(final int groupPosition) {
    return entries[groupPosition].getKey();
}

@Override
public int getGroupCount() {
    final int groupCount = entries.length;

    return groupCount;
}

@Override
public long getGroupId(final int groupPosition) {
    return groupPosition;
}

@Override
public View getGroupView(final int groupPosition, final boolean isExpanded,
        final View theConvertView, final ViewGroup parent) {
    View resultView = theConvertView;

    ViewHolder holder = null;

    if (resultView == null) {
        resultView = inflater.inflate(R.layout.group_layout, null);

        holder = new ViewHolder();
        holder.groupTextLabel = (TextView) resultView
                .findViewById(R.id.tvGroup);

        resultView.setTag(holder);
    } else {
        holder = (ViewHolder) resultView.getTag();
    }

    final Object item = getGroup(groupPosition);

    holder.groupTextLabel.setText(item.toString());

    return resultView;
}

@Override
public boolean hasStableIds() {
    return true;
}

@Override
public boolean isChildSelectable(final int groupPosition,
        final int childPosition) {
    return true;
}

}

于 2012-08-10T07:12:36.907 に答える
0

最初に展開可能なリストの main.xml を作成し、

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

    android:layout_height="match_parent" >

    <ExpandableListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:groupIndicator="@drawable/group_indicator"

        android:layout_weight="1" >
    </ExpandableListView>      
</TextView>    



</LinearLayout>

次に、group_row.xml の xml を作成し、

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

<TextView 
    android:id="@+id/tvGroupName" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:textStyle="bold"
android:layout_gravity="center_vertical"
    android:paddingLeft="30dp"
    android:gravity="center_vertical" />
</LinearLayout>

次に、child_row.xml のコードを記述します。

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


<TextView
    android:id="@+id/tvPlayerName" 
    android:paddingLeft="50dp"   
    android:layout_width="wrap_content" 
    android:layout_height="30dip" 

    android:gravity="center_vertical">

</TextView>    
</LinearLayout>

drawable フォルダーに group_indicator.xml ファイルを作成して、展開可能なリストのスタイルを定義します。

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

    <item android:state_empty="true" android:drawable="@android:color/transparent"></item>

    <item android:state_expanded="true" android:drawable="@android:color/transparent"></item>
    <item android:drawable="@android:color/transparent"></item>
</selector>

ExpList.java Activity クラスを作成してコードを記述し、

import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;

public class ExpList extends ExpandableListActivity
{

    static final String arrGroupelements[] = 
        {
        "India",
        "Australia",
        "England",
        "South Africa"
        };

    static final String arrChildelements[][] = 
        {
        {
            "Sachin Tendulkar",
            "Raina",
            "Dhoni",
            "Yuvi"
        },
        {
            "Ponting",
            "Adam Gilchrist",
            "Michael Clarke"
        },
        {
            "Andrew Strauss",
            "kevin Peterson",
            "Nasser Hussain"
        },
        {
            "Graeme Smith",
            "AB de villiers",
            "Jacques Kallis"
        }
        };

    DisplayMetrics metrics;
    int width;
    ExpandableListView expList;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        expList = getExpandableListView();
        metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        width = metrics.widthPixels;

//        this code for adjusting the group indicator into right side of the view
        expList.setIndicatorBounds(width - GetDipsFromPixel(50), width - GetDipsFromPixel(10));
        expList.setAdapter(new ExpAdapter(this));


        int groupPosition = 0;
        expList.expandGroup(0);

//        if (listView.isGroupExpanded(groupPosition))
//            listView.collapseGroup(groupPosition);
//        else
//            listView.expandGroup(groupPosition);

        expList.setOnGroupExpandListener(new OnGroupExpandListener()
        {
            @Override
            public void onGroupExpand(int groupPosition) 
            {
                Log.d("onGroupExpand", "OK");
            }
        });

        expList.setOnGroupCollapseListener(new OnGroupCollapseListener()
        {
            @Override
            public void onGroupCollapse(int groupPosition) 
            {
                Log.d("onGroupCollapse", "OK");
            }
        });

        expList.setOnChildClickListener(new OnChildClickListener()
        {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) 
            {
                Toast.makeText(getApplicationContext(), "" +  childPosition , Toast.LENGTH_LONG).show();
                Log.d("OnChildClickListener", "OK");
                return false;
            }
        });
    }

    public int GetDipsFromPixel(float pixels)
    {
//      Get the screen's density scale
        final float scale = getResources().getDisplayMetrics().density;
//      Convert the dps to pixels, based on density scale
        return (int) (pixels * scale + 0.5f);
    }
}

最後に、Expandable List 用のアダプター ExpAdapter.java を作成します。

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

public class ExpAdapter extends BaseExpandableListAdapter {

    static final String arrGroupelements[] = 
    {
   "India",
   "Australia",
   "England",
   "South Africa"
 };

    /**
  * strings for child elements
  */
 static final String arrChildelements[][] = 
 {
   {
  "Sachin Tendulkar",
  "Raina",
  "Dhoni",
  "Yuvi"
   },
   {
  "Ponting",
  "Adam Gilchrist",
  "Michael Clarke"
   },
   {
  "Andrew Strauss",
  "kevin Peterson",
  "Nasser Hussain"
   },
   {
  "Graeme Smith",
  "AB de villiers",
  "Jacques Kallis"
   }
    };
      private Context myContext;
      public ExpAdapter(Context context) {
       myContext = context;
      }
      @Override
      public Object getChild(int groupPosition, int childPosition) {
       return null;
      }

      @Override
      public long getChildId(int groupPosition, int childPosition) {
       return 0;
      }

      @Override
      public View getChildView(int groupPosition, int childPosition,
        boolean isLastChild, View convertView, ViewGroup parent) {

       if (convertView == null) {
        LayoutInflater inflater =  (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.child_row, null);
       }

       TextView tvPlayerName = (TextView) convertView.findViewById(R.id.tvPlayerName);
       tvPlayerName.setText(arrChildelements[groupPosition][childPosition]);

       return convertView;
      }

      @Override
      public int getChildrenCount(int groupPosition) {
       return arrChildelements[groupPosition].length;
      }

      @Override
      public Object getGroup(int groupPosition) {
       return null;
      }

      @Override
      public int getGroupCount() {
       return arrGroupelements.length;
      }

      @Override
      public long getGroupId(int groupPosition) {
       return 0;
      }

      @Override
      public View getGroupView(int groupPosition, boolean isExpanded,
        View convertView, ViewGroup parent) {

       if (convertView == null) {
        LayoutInflater inflater =  (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.group_row, null);
       }

       TextView tvGroupName = (TextView) convertView.findViewById(R.id.tvGroupName);
       tvGroupName.setText(arrGroupelements[groupPosition]);

       return convertView;
      }

      @Override
      public boolean hasStableIds() {
       return false;
      }

      @Override
      public boolean isChildSelectable(int groupPosition, int childPosition) {
       return true;
      }
     }

さあ、コードをコンパイルして実行します。それが役に立てば幸い。

于 2012-08-28T10:38:54.360 に答える