水平滚动网格视图

时间:2011-04-20 05:03:59

标签: android gridview scroll

我知道在Android中无法水平滚动网格视图。但我正在做的是在水平滚动视图中动态添加图像按钮,如下所示:

public class HorizontalScroller extends Activity {
    static int l=0;
     private Rect mTempRect = new Rect();

    static int r1=0;
    static int t=0;
    static int b=0;
    static int x=0;
    static int y=0;
 //Button[]  b1 = new Button[100];
    ImageButton btn[][] = new ImageButton[10][10];

 //ImageButton b1 = new ImageButton(this);
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LinearLayout rl = (LinearLayout)findViewById(R.id.widget92);

        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

        for(int i=0;i<4;i++)
        {
            for(int j=0;j<10;j++)
            {System.out.println("helo");
        /*      l=l+100;
                r1=r1+100;
                t=t+100;
                b=b+100;*/
            //button();
       //ImageButton btn=new ImageButton(this);
   /*    Rect r = mTempRect;
           r.left=10;
           r.top=10;
           r.right=10;
           r.bottom=10;
       btn[i][j].getDrawingRect(r);*/

            //btn[i][j].setId(j);

              Rect r = mTempRect;
              r.set(0,0,0,0);
              Rect r2 = mTempRect;
              r2.set(0,20,0,20);

                btn[i][j]=new ImageButton(this);
                btn[i][j]. setBackgroundResource(R.drawable.icon);
                btn[i][j].setMinimumWidth(20);
                btn[i][j].setMinimumHeight(20);
                params1.setMargins(5, 5, 5,5); 
                rl.addView(btn[i][j],params1); 

               System.out.println("1="+btn[i][j].getTop());
               System.out.println("2="+btn[i][j].getLeft());
               System.out.println("3="+btn[i][j].getRight());
               System.out.println("4="+btn[i][j].getBottom());
            }
        }
    }
}

但是我将所有图像按钮放在一行中。如何在类似网格的结构中实现它们?

6 个答案:

答案 0 :(得分:31)

实现水平滚动GridView涉及将一些Android源代码类复制到您的代码库(AdapterView,AbsListView,GridView,ScrollBarDrawable)并添加代码来处理水平代码。这主要是复制一些代码并从上到下,从下到右等进行更改。必须复制而不是扩展的主要原因是这些类的最终性质。

我前一段时间实现了一个水平滚动的GridView,最后还是推到了github: https://github.com/jess-anders/two-way-gridview

答案 1 :(得分:11)

你可以

  • TableLayout
  • 中使用HorizontalScrollView
  • 使用水平LinearLayout保持您的方法,但添加垂直LinearLayout而不是直接添加图像。例如,纵向每纵向LinearLayout添加三到四个图像,并重绘以在横向中仅添加两个。

我会首先尝试TableLayout方法。

PS1:下次尝试删除所有不相关的代码(代码越少,理解你所做的就越容易)。

PS2:请注意,System.out通常会重定向到/dev/null并因此丢失,因此我强烈建议您改为使用Log.d

完整示例

将其改编为onCreate()方法或您需要的任何地方:

public void horizontalScrollGalleryLayout () {
    HorizontalScrollView sv = new HorizontalScrollView(this);
    LinearLayout llh = new LinearLayout(this);
    llh.setOrientation(LinearLayout.HORIZONTAL);
    LinearLayout.LayoutParams layoutParamsTV = new LinearLayout.LayoutParams(40, 40);
    LinearLayout.LayoutParams layoutParamsLL = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    for (int i=0; i<20; i++) {
        LinearLayout llv = new LinearLayout(this);
        llv.setOrientation(LinearLayout.VERTICAL);
        TestView testView1 = new TestView(this, Color.rgb(i*12, 0, 0));
        TestView testView2 = new TestView(this, true, Color.rgb(i*12, i*12, 0));
        TestView testView3 = new TestView(this, true, Color.rgb(0, i*12, 0));
        llv.addView(testView1, layoutParamsTV);
        llv.addView(testView2, layoutParamsTV);
        llv.addView(testView3, layoutParamsTV);
        llh.addView(llv, layoutParamsLL);
    }
    sv.addView(llh, layoutParamsLL);
    setContentView(sv);
}

我使用一个非常简单的视图作为例子:

public class TestView extends View {
Context context;
int color;

public TestView(Context context, int color) {
    super(context);
    this.context = context;
    this.color = color;
}

@Override
public void onDraw (Canvas canvas) {
    super.onDraw(canvas);
    this.setBackgroundColor(Color.LTGRAY);
    Paint paint = new Paint (Paint.ANTI_ALIAS_FLAG);
    paint.setColor(color);
    canvas.drawCircle(20, 20, 20, paint);
}
}

答案 2 :(得分:11)

有一个非常简单的技巧。

  1. 将网格视图旋转270度并将列数设置为2.
  2. 将每个项目旋转到90度(以便项目显示为原始方向)。
  3. 这可能对某些人有用!!

答案 3 :(得分:7)

我这样做了:

<强> activity_main.xml中

<HorizontalScrollView
   android:layout_width="match_parent"
   android:layout_height="wrap_content">

      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="horizontal">

          <GridView
             android:id="@+id/gridView"
             android:layout_width="match_parent"
             android:layout_height="wrap_content">
          </GridView>

      </LinearLayout>

</HorizontalScrollView>

<强> MainActivity.java

GridView gridView = (GridView) findViewById(R.id.gridView);

gridView.setNumColumns(arrayList.size());

GridViewAdapter gridViewAdapter = new GridViewAdapter(mContext, arrayList);
gridView.setAdapter(gridViewAdapter); 

// Set dynamic width of Gridview
setDynamicWidth(gridView);

添加以下方法

private void setDynamicWidth(GridView gridView) {
        ListAdapter gridViewAdapter = gridView.getAdapter();
        if (gridViewAdapter == null) {
            return;
        }
        int totalWidth;
        int items = gridViewAdapter.getCount();
        View listItem = gridViewAdapter.getView(0, null, gridView);
        listItem.measure(0, 0);
        totalWidth = listItem.getMeasuredWidth();
        totalWidth = totalWidth*items;
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        params.width = totalWidth;
        gridView.setLayoutParams(params);
 }

希望这会对你有所帮助。

答案 4 :(得分:3)

  

我已经发布了这个答案here,但这两个问题都是   相同...

从现在起,Android中有一个很好的解决方案:HorizontalGridView

1. Gradle依赖

dependencies {
    compile 'com.android.support:leanback-v17:23.1.0'
}

2.在布局中添加

<强> your_activity.xml

<!-- your stuff before... -->
        <android.support.v17.leanback.widget.HorizontalGridView
            android:layout_width="wrap_content"
            android:layout_height="80dp"
            android:id="@+id/gridView"
            />
<!-- your stuff after... -->

3.布局网格元素

为您的网格元素( grid_element.xml )创建布局。我创建了一个只有一个按钮的简单文件。

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button" />
</LinearLayout>

4.创建适配器

受此链接的启发:https://gist.github.com/gabrielemariotti/4c189fb1124df4556058

public class GridElementAdapter extends RecyclerView.Adapter<GridElementAdapter.SimpleViewHolder>{

    private Context context;
    private List<String> elements;

    public GridElementAdapter(Context context){
        this.context = context;
        this.elements = new ArrayList<String>();
        // Fill dummy list
        for(int i = 0; i < 40 ; i++){
            this.elements.add(i, "Position : " + i);
        }
    }

    public static class SimpleViewHolder extends RecyclerView.ViewHolder {
        public final Button button;

        public SimpleViewHolder(View view) {
            super(view);
            button = (Button) view.findViewById(R.id.button);
        }
    }

    @Override
    public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final View view = LayoutInflater.from(this.context).inflate(R.layout.grid_element, parent, false);
        return new SimpleViewHolder(view);
    }

    @Override
    public void onBindViewHolder(SimpleViewHolder holder, final int position) {
        holder.button.setText(elements.get(position));
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, "Position =" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

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

    @Override
    public int getItemCount() {
        return this.elements.size();
    }
}

5.在您的活动中初始化它:

private HorizontalGridView horizontalGridView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity);
    horizontalGridView = (HorizontalGridView) findViewById(R.id.gridView);
    GridElementAdapter adapter = new GridElementAdapter(this);

    horizontalGridView.setAdapter(adapter);
}

答案 5 :(得分:2)

使用recyclerview将其gridlayout设置为布局管理器并将其设置为水平滚动

your recycle view.setLayoutManager(new GridLayoutManager(getActivity(),2, LinearLayoutManager.HORIZONTAL, false))

这里2是网格的列跨度