水平滚动网格视图

如何解决水平滚动网格视图

| 我知道在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);
              Rect r2 = mTempRect;
              r2.set(0,20,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); 
                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());
            }
        }
    }
}
但我将所有图像按钮都放在一行中。如何在类似网格的结构中实现它们?

解决方法

您可以 在
HorizontalScrollView
中使用
TableLayout
,或者 保持水平
LinearLayout
不变,但增加垂直
LinearLayout
而不是直接添加图像。例如,纵向每3ѭ纵向添加三到四个图像,然后重新绘制以横向仅添加两个。 我将首先尝试“ 1”法。 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));
        TestView testView2 = new TestView(this,true,i*12,0));
        TestView testView3 = new TestView(this,Color.rgb(0,0));
        llv.addView(testView1,layoutParamsTV);
        llv.addView(testView2,layoutParamsTV);
        llv.addView(testView3,layoutParamsTV);
        llh.addView(llv,layoutParamsLL);
    }
    sv.addView(llh,layoutParamsLL);
    setContentView(sv);
}
我以一个非常简单的View为例:
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,paint);
}
}
,实现水平滚动的GridView涉及将一些Android源代码类复制到您的代码库中(AdapterView,AbsListView,GridView,ScrollBarDrawable),并添加代码以处理水平代码。这主要是复制一些代码并从上到左,从下到右等。需要复制而不是扩展的主要原因是这些类的最终性质。 不久前,我实现了一个水平滚动的GridView,最终解决了推到github的问题: https://github.com/jess-anders/two-way-gridview,有一个很简单的把戏。 将网格视图旋转270度,并将列数设置为2。 将每个项目旋转90度(以使项目显示为原始方向)。 这可能对某些人有用!,我这样做: 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);
 }
希望这会帮助你。,我已经在这里发布了这个答案,但是两个问题都是 相同... 从现在开始,Android中有一个不错的解决方案:Horizo​​ntalGridView。 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);
}
,使用recyclerview并将其gridlayout设置为布局管理器并将其设置为水平滚动
your recycle view.setLayoutManager(new GridLayoutManager(getActivity(),2,LinearLayoutManager.HORIZONTAL,false))
这里2是网格的列跨度

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res