如何在片段中使用listView?

时间:2014-08-05 13:52:14

标签: java android listview android-fragments

我正在尝试在Fragment中使用listview,但是当我按下所选行时它不起作用。

// Group1ListViewFragment.java

private ListView listview1;

public Group1ListViewFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) { 

    View rootView = inflater.inflate(R.layout.group1_list_view_fragment, container, false);

    Team[] team_data = new Team[]
    {
        new Team(R.drawable.ic_launcher, "Arsenal"),
        new Team(R.drawable.ic_launcher, "Chelsea"),
        new Team(R.drawable.ic_launcher, "Everton"),
        new Team(R.drawable.ic_launcher, "Liverpool"),
        new Team(R.drawable.ic_launcher, "Manchester United")
    };

    ListView listview1 = (ListView)rootView.findViewById(R.id.listView1);

    // Using the adapter to connect between item view and the photo array
    listview1.setAdapter(new TeamAdapter(getActivity(), 0, team_data));


    return rootView;
}

另外,我做了一个连接listView和数组的适配器 这是TeamAdapter.java

public TeamAdapter(Context context, int layoutResourceId, Team[] data) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    TeamHolder holder = null;

    if (row == null) {
        // LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        // Ref: http://stackoverflow.com/questions/7803771/call-to-getlayoutinflater-in-places-not-in-activity
        LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        row = inflater.inflate(layoutResourceId, parent, false);

        holder = new TeamHolder();
        holder.imgIcon = (ImageView) row.findViewById(R.id.imgIcon);
        holder.txtTitle = (TextView) row.findViewById(R.id.txtTitle);

        row.setTag(holder);
    } else {
        holder = (TeamHolder) row.getTag();
    }

    Team team = data[position];
    holder.txtTitle.setText(team.title);
    holder.imgIcon.setImageResource(team.icon); 
    return row;
}

static class TeamHolder {
    ImageView imgIcon;
    TextView txtTitle;
}

1 个答案:

答案 0 :(得分:0)

你忘记了适配器类中的传递列表视图行Xml

替换

listview1.setAdapter(new TeamAdapter(getActivity(), 0, team_data));

listview1.setAdapter(new TeamAdapter(getActivity(), R.layout.yourrowxml, team_data));

多数民众赞成......