即使 getCount() 有结果也不会调用 getView()

getView() not called even when getCount() has results

对不起我的英语,不是我的母语。 我在 Android 中创建应用程序,但遇到问题:

我有一个 TabBar,其中包含 2 个片段(1 - ProductFragment 和 2 - CartFragment),在第二个片段 (CartFragment) 中,我有一个 ListView 并且 ListView 是初始 null.

CartFragment 布局:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:padding="15dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

               <ListView
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:id="@+id/lancarvenda_carrinho_lvwresultado"
                   android:orientation="vertical" />

    </LinearLayout>
</FrameLayout>

ProductFragment 中我有一个带有 onclick 的按钮,那个 onclick Intents 另一个 activity 在那个 activity 我添加了值在我的 public 自定义列表中:

public static List<PesquisarProdutoResponse> Carrinho = new ArrayList<>();

当我完成添加我需要的值后,我将 activity 和 return 关闭到 TabBar 并期望 ListView 已填充。

填充我的 public 列表的方法:

private void PesquisarProduto()
{
    RequestQueue sQueue = Volley.newRequestQueue(getActivity());
    String sEnderecoBase = "http://www.my-url";

    StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
        @Override
        public void onResponse(String response)
        {
            PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
            if (sResultado.getCodigoRetorno() != 0)
            {
                //lastText = "Produto não encontrado";
                //barcodeView.setStatusText("Produto não encontrado");
            }
            else
            {

                Variaveis.Carrinho.add(sResultado);

                try {
                    List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar = new ArrayList<>();

                    for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
                        PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
                        sCarrinhoAuxiliar.add(sItem);
                    }

                    LancarVendaCarrinhoListViewAdapter sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(),
                            sCarrinhoAuxiliar);
                    fCarrinhoResultado.setAdapter(sAdaptador);
                    sAdaptador.notifyDataSetChanged();

                    Object oi = fCarrinhoResultado.getCount();
                    oi.toString();

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }, new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            byte[] sBytesResposta = error.networkResponse.data;
            String sTexto = new String(sBytesResposta);
            Mensagem.ExibirAlert(getActivity(), String.valueOf(error.networkResponse.statusCode));
        }
    })
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError
        {
            Map<String, String> sHeaders = new HashMap<>();
            sHeaders.put("Authorization", "Bearer " + Variaveis.ApiToken);
            return sHeaders;
        }

        @Override
        public byte[] getBody() throws AuthFailureError
        {
            return new Gson().toJson(sCorpoBusca).getBytes();
        }

        @Override
        public String getBodyContentType()
        {
            return "application/json";
        }
    };

    sQueue.add(sRequest);
}

列表视图适配器:

public class LancarVendaCarrinhoListViewAdapter extends BaseAdapter
{

private Context mContext;
//private LayoutInflater mInflater;
private List<PesquisarProdutoObjetoRetorno> mDataSource;

public LancarVendaCarrinhoListViewAdapter(Context context, List<PesquisarProdutoObjetoRetorno> items)
{
    mContext = context;
    mDataSource = items;
}

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

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    try
    {
        LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View sView = mInflater.inflate(R.layout.activity_lancarvenda_carrinho_list_view_item, parent, false);

        PesquisarProdutoObjetoRetorno sItem = (PesquisarProdutoObjetoRetorno) getItem(position);

        TextView descricao = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txtdescricao);
        descricao.setText(sItem.getDescricao());

        TextView preco = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txvpreco);
        preco.setText(String.valueOf(sItem.getPreco()));

        EditText quantidade = (EditText)sView.findViewById(R.id.lancarvenda_carrinho_item_etquantidade);
        quantidade.setText("1");

        return sView;
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
}
}

我的行布局:

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

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

        <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/lancarvenda_carrinho_item_imvFoto"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center_horizontal"
            android:background="@drawable/circulo_foto2"
            app:border_color="#898989"
            app:border_width="2dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginLeft="10dp">

            <TextView
                android:id="@+id/lancarvenda_carrinho_item_txtdescricao"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:text="Relogio"
                android:textSize="20dp"
                android:textStyle="bold"
                android:layout_marginRight="8dp"
                android:lines="2"
                android:minLines="2"
                android:singleLine="false"/>

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

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

                    <TextView
                        android:id="@+id/lancarvenda_carrinho_item_txvpreco"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="8dp"
                        android:text="R$ 399,89"
                        android:textColor="#1ba39c"
                        android:textSize="20dp"
                        android:layout_marginRight="70dp"/>

                    <EditText
                        android:id="@+id/lancarvenda_carrinho_item_etquantidade"
                        android:layout_width="50dp"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:backgroundTint="#9a9b9c"
                        android:hint="0"
                        android:textColor="#2a2d2e"
                        android:layout_marginRight="8dp"/>

                </RelativeLayout>

            </LinearLayout>
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

在调试模式下,当代码在 Adapter 中传入 getCount 时,我的大小大于 1,但我的列表仍然没有显示!即使我关闭 TabBar 并重新打开并在 onCreate 方法上设置适配器(带值)。 我可以对 ListView 节目做些什么?

编辑 我在 onCreate 上给 listview 充气:

    super.onCreate(savedInstanceState);

    LayoutInflater sInflater = getActivity().getLayoutInflater();
    View sView = sInflater.inflate(R.layout.fragment_lancarvenda_carrinho, null);

    fCarrinhoResultado = (ListView) sView.findViewById(R.id.lancarvenda_carrinho_lvwresultado);

尝试使您的列表成为 class 的成员而不是局部变量

private void PesquisarProduto()
{
    RequestQueue sQueue = Volley.newRequestQueue(getActivity());
    String sEnderecoBase = "http://www.my-url";

    StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {

        // Make cart list a private data member so it doesn't loose scope //
        List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar; 

        @Override
        public void onResponse(String response)
        {
            PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
            if (sResultado.getCodigoRetorno() != 0)
            {
                //lastText = "Produto não encontrado";
                //barcodeView.setStatusText("Produto não encontrado");
            }
            else
            {

                Variaveis.Carrinho.add(sResultado);

                try {
                    sCarrinhoAuxiliar = new ArrayList<>();
                    ...
                }
                ...
             }
             ...
         }
         ...
     }
     ...
}

将您的列表 sCarrinhoAuxiliar 和适配器 sAdaptador 声明为 global

更新您的 OnCreateView() 如下:

// Global
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;
LancarVendaCarrinhoListViewAdapter sAdaptador;

.........................

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

    ....................
    ........................

    sCarrinhoAuxiliar = new ArrayList<>();
    sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(), sCarrinhoAuxiliar);
    fCarrinhoResultado.setAdapter(sAdaptador);

    .......................
    ...............
}

更新您的 onResponse() 方法如下:

@Override
public void onResponse(String response) {

    .....................
    ..........................
    try {
        // Clear old data
        sCarrinhoAuxiliar.clear();

        for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
            PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
            sCarrinhoAuxiliar.add(sItem);
        }
        // Update list        
        sAdaptador.notifyDataSetChanged();
        .............
        ....................
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

希望对你有所帮助~

我从另一个论坛得到了帮助,我能够解决我的问题:

我重写了两个方法:OnCreate(膨胀并接收视图)和 OnCreateView(找到产品并放入列表视图),我删除了方法 OnCreate 并将所有内容都放在 OnCreateView 上!

解决了我的问题! 谢谢大家!