使用RecyclerView添加到GridLayout的动态按钮是相互添加的 [英] Dynamic buttons added to a GridLayout using RecyclerView are added on top of each other

查看:917
本文介绍了使用RecyclerView添加到GridLayout的动态按钮是相互添加的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加动态按钮到网格布局,如下所示。 每个按钮一次添加一个,并且布局必须更新自己以使行中的按钮。 我的问题是,当添加一个新按钮时,它会显示在添加的最后一个按钮的顶部,而不是以行格式放置。在下面的图像中,我显示了我想要的和当前正在发生的事情标有数字的方格是我的按钮。在我所拥有的图像中,我已经添加了6个按钮到布局,但是它们都在彼此之间。

I want to add dynamic buttons to a grid layout as shown below. Each button is added one at a time, and the layout must update itself to have the buttons in rows. My problem is that when a new button is added it appears on top of the last button added, and is not placed in a row format. In this image below I show what I want and what is currently happening, where the squares labeled with numbers are my buttons. In the image of what I have, I have added 6 buttons to the layout, but they are all on top of each other.

我已经看了一下如何做到这一点,建议我使用一个 RecyclerView 一个 GridLayoutManager 。我已经将其添加到我的代码中,但是像我说的那样,问题是当我添加一个按钮,然后如果我添加另一个按钮,第二个添加到第一个。如果我的按钮是预设的,而不是动态按钮,则可以使用。

I have looked around about how to do this, and it was recommended to me that I use a RecyclerView with a GridLayoutManager. I have added this to my code, but like I said the problem is that when I add a button, and then if I add another button, the second one is added on top of the first. What I have works if my buttons are preset, but not for dynamic buttons.

这是我的代码:

主片段启动 RecyclerView 。我有另一个启动 createButton()方法的活动,并传递一个 drawable String 。这些可绘制和字符串一次根据用户的操作一次传递给该方法,并一次创建一个图像按钮。

Main Fragment initiates the RecyclerView. I have another activity that initiates createButton() method and passes a drawable and String. These drawables and strings are passed to this method one at a time based on the user's action, and create an image button one at a time.

public class MyFragment extends Fragment {

    private GridLayoutManager lLayout;

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

    }

    // onCreateView
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.my_fragment, container, false);

        // Get screen size to have different layouts for phone and tablet
        int screenSize = getResources().getConfiguration().screenLayout &
                Configuration.SCREENLAYOUT_SIZE_MASK;

        String toastMsg;
        switch (screenSize) {
            case Configuration.SCREENLAYOUT_SIZE_LARGE:
                toastMsg = "Large screen";
                Log.d("tag_name", "Large screen");
                break;
            case Configuration.SCREENLAYOUT_SIZE_NORMAL:
                toastMsg = "Normal screen";
                Log.d("tag_name", "Normal screen");
                break;
            case Configuration.SCREENLAYOUT_SIZE_SMALL:
                toastMsg = "Small screen";
                Log.d("tag_name", "Small screen");
                break;
            default:
                toastMsg = "Screen size is neither large, normal or small";
                Log.d("tag_name", "Screen size is not large, normal, or small");
        }
        Toast.makeText(getActivity(), toastMsg, Toast.LENGTH_LONG).show();

        // Create an empty list to initialize the adapter (or else get nullPointerException error)
        List<ItemObject> myList = new ArrayList<ItemObject>();

        // 3 rows for tablet
        // 2 rows for phone

        if (screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE
                || screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
            lLayout = new GridLayoutManager(getActivity(), 3, GridLayoutManager.HORIZONTAL, false);
        } else
            lLayout = new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);

        RecyclerView rView = (RecyclerView) view.findViewById(R.id.recycler_view);

        rView.setHasFixedSize(true);
        rView.setLayoutManager(lLayout);

        RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getActivity(), myList);
        rView.setAdapter(rcAdapter);

        return view;
    }

    private List<ItemObject> getAllItemList(String applicationName, Drawable app_drawable) {

        List<ItemObject> allItems = new ArrayList<ItemObject>();
        allItems.add(new ItemObject(applicationName, app_drawable));

        return allItems;
    }

    public void createButton(Drawable d, String appName) {

        List<ItemObject> rowListItem = getAllItemList(appName, d);
        lLayout = new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);


        RecyclerView rView = (RecyclerView) getView().findViewById(R.id.recycler_view);
        rView.setHasFixedSize(true);
        rView.setLayoutManager(lLayout);

        RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getActivity(), rowListItem);
        rView.setAdapter(rcAdapter);

    }

}

我的布局my_fragment):

My layout (my_fragment):

<LinearLayout android:id="@+id/my_fragment"
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_marginTop="15dp"
          android:gravity="center_horizontal">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scrollbars="horizontal"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageButton
            android:id="@+id/new_app_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/new_app_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/new_app_button"
            android:gravity="center"/>

    </RelativeLayout>
</LinearLayout>

编辑

这是MyFragment的更新代码
现在,当第二个ImageButton被添加时,我收到一个nullPointerException

HERE IS MY UPDATED CODE FOR MyFragment Now I am getting a nullPointerException when the second ImageButton gets added

public class MyFragment extends Fragment {

private GridLayoutManager lLayout;

private ButtonCreator bc;
RecyclerViewAdapter rcAdapter;


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

    List<ItemObject> myList = new ArrayList<ItemObject>();
    rcAdapter = new RecyclerViewAdapter(getActivity(),myList);

}

// onCreateView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.home_fragment, container, false);


    // Get screen size so we can have different layouts for phone and tablet
    int screenSize = getResources().getConfiguration().screenLayout &
            Configuration.SCREENLAYOUT_SIZE_MASK;

    String toastMsg;
    switch(screenSize) {
        case Configuration.SCREENLAYOUT_SIZE_LARGE:
            toastMsg = "Large screen";
            Log.d("tag_name", "Large screen");
            break;
        case Configuration.SCREENLAYOUT_SIZE_NORMAL:
            toastMsg = "Normal screen";
            Log.d("tag_name", "Normal screen");
            break;
        case Configuration.SCREENLAYOUT_SIZE_SMALL:
            toastMsg = "Small screen";
            Log.d("tag_name", "Small screen");
            break;
        default:
            toastMsg = "Screen size is neither large, normal or small";
            Log.d("tag_name", "Screen size is not large, normal, or small");
    }
    Toast.makeText(getActivity(), toastMsg, Toast.LENGTH_LONG).show();


    // Create an empty list to initialize the adapter (or else get nullPointerException error)

    if (screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE
    || screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
        lLayout = new GridLayoutManager(getActivity(), 3, GridLayoutManager.HORIZONTAL, false);
    }

    else lLayout = new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);


    RecyclerView rView = (RecyclerView)view.findViewById(R.id.recycler_view);

    rView.setHasFixedSize(true);
    rView.setLayoutManager(lLayout);


    rView.setAdapter(rcAdapter);


    return view;
}

private List<ItemObject> getAllItemList(String applicationName, Drawable app_drawable){

    List<ItemObject> allItems = new ArrayList<ItemObject>();
    allItems.add(new ItemObject(applicationName, app_drawable));


    return allItems;
}


public void createButton (Drawable d, String appName){

    rcAdapter.addItem(new ItemObject(appName , d));

}



// In order to get the view of HomeFragment correctly

public interface ButtonCreator{
    void buttonCreator(Drawable d, String string);
}



@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    bc = (ButtonCreator) activity;
}

}

MyFragment中的createButton方法(在runOnUiThread方法中调用)

public class MainActivity extends FragmentActivity implements MyFragment.ButtonCreator {


private Thread repeatTaskThread;
private byte[] byteArray;

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

   FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
   ft.replace(R.id.container, new MyFragment()).commit();
}


public void buttonCreator(Drawable d,String a) {
    MyFragment homeFragment = (MyFragment)getSupportFragmentManager().getFragments().get(1);
    homeFragment.createButton(d, a);
}

public void RepeatTask(){

     repeatTaskThread = new Thread() {
        public void run() {
           while (true) {


              try {


                 System.out.println("TRY_1");

                 Socket socket = new Socket("192.168.0.26", 5050);

                 // Get data sent through socket
                 DataInputStream DIS = new DataInputStream(socket.getInputStream());

                 System.out.println("DataInputStream Started");

                 // read data that got sent
                 final String applicationName = DIS.readUTF();


                 // read array data for bitmap

                 int len = DIS.readInt();
                 byte[] data = new byte[len];

                 DIS.readFully(data, 0, data.length);


                 Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                 final Drawable d = new BitmapDrawable(getResources(), bitmap);


                  runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       // TODO Auto-generated method stub


                       Log.d("tag_name", "Try_2");

                        buttonCreator(d,applicationName);


                    }
                 });


                 socket.close();




              } catch (Exception e) {


                 System.out.println("Exception is " + e.toString());

              }


              try {
                 // Sleep for 5 seconds
                 Thread.sleep(5000);
              } catch (Exception e) {
                 e.printStackTrace();
              }
           }
        }

        ;
     };
     repeatTaskThread.start();


}

}

我的应用程序在第二个按钮创建时崩溃时发生错误:

MY error when my app crashes on the second button creation:

05-11 17:05:25.275 14257-14257/it.anddev.bradipao.janus E/RecyclerView: No adapter attached; skipping layout
05-11 17:05:25.275 14257-14257/it.anddev.bradipao.janus D/AndroidRuntime: Shutting down VM
05-11 17:05:25.275 14257-14257/it.anddev.bradipao.janus W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x437c0160)
05-11 17:05:25.305 14257-14257/it.anddev.bradipao.janus E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: it.anddev.bradipao.janus, PID: 14257
                                                                      java.lang.NullPointerException
                                                                          at android.support.v7.widget.RecyclerView.computeHorizontalScrollRange(RecyclerView.java:1518)
                                                                          at android.view.View.onDrawScrollBars(View.java:12248)
                                                                          at android.view.View.draw(View.java:14794)
                                                                          at android.support.v7.widget.RecyclerView.draw(RecyclerView.java:3171)
                                                                          at android.view.View.getDisplayList(View.java:13655)
                                                                          at android.view.View.getDisplayList(View.java:13697)
                                                                          at android.view.View.draw(View.java:14505)
                                                                          at android.view.ViewGroup.drawChild(ViewGroup.java:3134)
                                                                          at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2971)
                                                                          at android.view.View.getDisplayList(View.java:13650)
                                                                          at android.view.View.getDisplayList(View.java:13697)
                                                                          at android.view.View.draw(View.java:14505)
                                                                          at android.view.ViewGroup.drawChild(ViewGroup.java:3134)
                                                                          at android.support.v7.widget.RecyclerView.drawChild(RecyclerView.java:3693)
                                                                          at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2971)
                                                                          at android.view.View.draw(View.java:14791)
                                                                          at android.support.v7.widget.RecyclerView.draw(RecyclerView.java:3171)
                                                                          at android.view.View.getDisplayList(View.java:13655)
                                                                          at android.view.View.getDisplayList(View.java:13697)
                                                                          at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3108)
                                                                          at android.view.View.getDisplayList(View.java:13593)
                                                                          at android.view.View.getDisplayList(View.java:13697)
                                                                          at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3108)
                                                                          at android.view.View.getDisplayList(View.java:13593)
                                                                          at android.view.View.getDisplayList(View.java:13697)
                                                                          at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3108)
                                                                          at android.view.View.getDisplayList(View.java:13593)
                                                                          at android.view.View.getDisplayList(View.java:13697)
                                                                          at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3108)
                                                                          at android.view.View.getDisplayList(View.java:13593)
                                                                          at android.view.View.getDisplayList(View.java:13697)
                                                                          at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3108)
                                                                          at android.view.View.getDisplayList(View.java:13593)
                                                                          at android.view.View.getDisplayList(View.java:13697)
                                                                          at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3108)
                                                                          at android.view.View.getDisplayList(View.java:13593)
                                                                          at android.view.View.getDisplayList(View.java:13697)
                                                                          at android.view.HardwareRenderer$GlRenderer.buildDisplayList(HardwareRenderer.java:1570)
                                                                          at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1449)
                                                                          at android.view.ViewRootImpl.draw(ViewRootImpl.java:2476)
                                                                          at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2300)
                                                                          at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1929)
                                                                          at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1043)
                                                                          at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
                                                                          at android.view.Choreographer$CallbackRecord.run(Choreographer.java:771)
                                                                          at android.view.Choreographer.doCallbacks(Choreographer.java:574)
                                                                          at android.view.Choreographer.doFrame(Choreographer.java:544)
                                                                          at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:757)
                                                                          at android.os.Handler.handleCallback(Handler.java:733)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                          at android.os.Looper.loop(Looper.java:149)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5257)
                                                                          at java.lang.reflect.Method.invokeNative(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:515)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
                                                                          at dalvik.system.NativeStart.main(Native Method)


推荐答案

做这样的事情

public class MyFragment extends Fragment {

    private GridLayoutManager lLayout;

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

    }

    // onCreateView
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.my_fragment, container, false);

        // Get screen size to have different layouts for phone and tablet
        int screenSize = getResources().getConfiguration().screenLayout &
                Configuration.SCREENLAYOUT_SIZE_MASK;

        String toastMsg;
        switch (screenSize) {
            case Configuration.SCREENLAYOUT_SIZE_LARGE:
                toastMsg = "Large screen";
                Log.d("tag_name", "Large screen");
                break;
            case Configuration.SCREENLAYOUT_SIZE_NORMAL:
                toastMsg = "Normal screen";
                Log.d("tag_name", "Normal screen");
                break;
            case Configuration.SCREENLAYOUT_SIZE_SMALL:
                toastMsg = "Small screen";
                Log.d("tag_name", "Small screen");
                break;
            default:
                toastMsg = "Screen size is neither large, normal or small";
                Log.d("tag_name", "Screen size is not large, normal, or small");
        }
        Toast.makeText(getActivity(), toastMsg, Toast.LENGTH_LONG).show();

        // Create an empty list to initialize the adapter (or else get nullPointerException error)

        // 3 rows for tablet
        // 2 rows for phone

        if (screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE
                || screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
            lLayout = new GridLayoutManager(getActivity(), 3, GridLayoutManager.HORIZONTAL, false);
        } else
            lLayout = new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);

        RecyclerView rView = (RecyclerView) view.findViewById(R.id.recycler_view);

        rView.setHasFixedSize(true);
        rView.setLayoutManager(lLayout);

        rView.setAdapter(rcAdapter);

        return view;
    }

    RecyclerViewAdapter rcAdapter;

    private List<ItemObject> getAllItemList(String applicationName, Drawable app_drawable) {

        List<ItemObject> allItems = new ArrayList<ItemObject>();
        allItems.add(new ItemObject(applicationName, app_drawable));

        return allItems;
    }

    public void createButton(Drawable d, String appName) {

        rcAdapter.addItem(new ItemObject(appName , d))

    }

}

在适配器中添加此方法



And in the adapter add this method

public void addItem(int position) {
        list.add(position);
        notifyItemInserted(position);
        notifyItemRangeChanged(position, list.size());
    }

编辑

为了防止警告,请尝试将适配器初始化移至onCreate

To prevent the warning try moving your adapter initialization to onCreate

@Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            List<ItemObject> myList = new ArrayList<ItemObject>();
            rcAdapter = new RecyclerViewAdapter(getActivity(), myList);
        }

这篇关于使用RecyclerView添加到GridLayout的动态按钮是相互添加的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆