android gridview

android gridview里怎么加进度条

小亿
88
2024-01-27 11:46:02
栏目: 编程语言

在Android GridView中添加进度条可以通过自定义Adapter来实现。以下是一个简单示例:

首先,创建一个自定义的Adapter类,继承自BaseAdapter:

public class CustomAdapter extends BaseAdapter {
    private Context mContext;
    private List<String> mData;
    private LayoutInflater mInflater;

    public CustomAdapter(Context context, List<String> data) {
        mContext = context;
        mData = data;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.grid_item, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.progressBar = convertView.findViewById(R.id.progress_bar);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        // 设置进度条的进度
        viewHolder.progressBar.setProgress(mData.get(position).getProgress());

        return convertView;
    }

    private static class ViewHolder {
        ProgressBar progressBar;
    }
}

然后,在grid_item.xml布局文件中添加一个进度条:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

最后,在Activity中使用GridView并设置Adapter:

public class MainActivity extends AppCompatActivity {
    private GridView mGridView;
    private CustomAdapter mAdapter;
    private List<String> mData = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化数据
        for (int i = 0; i < 10; i++) {
            mData.add(new ProgressItem(i * 10)); // 这里的ProgressItem是一个自定义的类,用于表示每个GridView项的进度值
        }

        // 初始化GridView和Adapter
        mGridView = findViewById(R.id.grid_view);
        mAdapter = new CustomAdapter(this, mData);
        mGridView.setAdapter(mAdapter);
    }
}

注意,你需要根据自己的需求修改和完善代码。这只是一个简单的示例,你可能需要根据实际情况进行适当的修改和调整。

0
看了该问题的人还看了