使用自定义适配器添加2按钮ListView

时间:2016-11-28 22:26:29

标签: java android xml listview android-studio

我在尝试将2个按钮添加到我的列表视图时遇到问题,我上传的图片包含我拥有的内容和我想要的内容

What i want

所以,我只是想在那里添加这两个按钮,但我一直在尝试使用自定义适配器,但我仍然无法做到,如果有人可以帮助我,我会非常感激它

到目前为止我的文件:

activity_vendor_main.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/activity_vendedor_main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:background="@color/colorPrimary"
    android:layout_height="match_parent"
    android:weightSum="1">


    <ImageView
        android:src="@drawable/logo"
        android:layout_width="209dp"
        android:layout_height="106dp"
        android:layout_marginBottom="20dp"
        android:layout_gravity="center_horizontal" />

    />
    <ImageView
        android:src="@drawable/orderid1"
        android:layout_width="134dp"
        android:layout_height="34dp"
        android:layout_gravity="center_horizontal"
        />

    <SearchView
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:id="@+id/seacrhBar"
        android:textColor="@color/colorVendor"
        android:layout_marginTop="25dp"
        android:background="@drawable/vendor_bars_background"/>


    <android.support.v7.widget.AppCompatButton
        android:text="AGREGAR ORDEN"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="8dp"
        android:textStyle="bold"
        android:textColor="@color/colorVendor"
        android:background="@drawable/single_button"
        android:id="@+id/add_order1"
        android:onClick="EVENTO" />


    <ListView
        android:layout_width="wrap_content"
        android:layout_height="190dp"
        android:id="@+id/tablaPedidos"
        android:choiceMode="singleChoice"
        android:layout_above="@+id/editText2"
        android:background="@drawable/vendor_bars_background"
        android:layout_weight="0.13" />

    <android.support.v7.widget.AppCompatButton
        android:text="CERRAR SESIÓN"
        android:layout_width="120sp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="135dp"
        android:textStyle="bold"
        android:textColor="@color/colorVendor"
        android:background="@drawable/button_login_form"
        android:id="@+id/signOut2_order_form"
        android:onClick="logout" />


</LinearLayout>

MainActivity.java

public class LoginActivity extends AppCompatActivity {

    GlobalClass appContext;
    @BindView(R.id.input_username)
    EditText _usernameText;
    @BindView(R.id.input_password)
    EditText _passwordText;
    @BindView(R.id.btn_login)
    Button _loginButton;
    ProgressDialog progressDialog;
    //Invocación de servicio para acceso al API
    UsersHandler client = ServiceGenerator.createService(UsersHandler.class);


    @Override
    public void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);



        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        ButterKnife.bind(this);
        appContext = (GlobalClass)getApplicationContext();
        _loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);

    }




    @Override
    public void onBackPressed() {
        moveTaskToBack(false);
    }

    public void onLoginSuccess() {
        _loginButton.setEnabled(true);
        finish();
    }

    public void onLoginFailed(String message) {
        Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
        _loginButton.setEnabled(true);
    }

    public void login() {
        if (!validate()) {
           // onLoginFailed("Login failed");
            return;
        }

        _loginButton.setEnabled(false);

        progressDialog = new ProgressDialog(LoginActivity.this,R.style.AppTheme_Dark_Dialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Autenticando...");
        progressDialog.show();

        new android.os.Handler().postDelayed(
                new Runnable() {
                    public void run() {
                        onLoginSuccess();
                        //progressDialog.dismiss();
                    }
                }, 3000);
        progressDialog.dismiss();
        String userType = appContext.getSessionUserType();
        loadUserView(userType);
    }

    public boolean validate() {
        boolean valid = true;
        String username = _usernameText.getText().toString().trim();
        String password = _passwordText.getText().toString();

        //if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(username).matches()) {
        if (username.isEmpty()) {
            _usernameText.setError("Ingrese un usuario válido.");
            valid = false;
        } else {
            _usernameText.setError(null);
        }

        if (password.isEmpty() || password.length() < 4) {
            _passwordText.setError("No menos de 4 caracteres alfanuméricos");
            valid = false;
        } else {
            _passwordText.setError(null);
        }

        if (valid) {
            valid = validateApi(1, username, password);
        }

        return valid;
    }

    public boolean validateApi(int i, String username, String password) {
        appContext.setSessionToken("1");
        appContext.setSessionUserType(Constants.COURIER);
        if (username.equals("v"))
            appContext.setSessionUserType(Constants.VENDOR);
        appContext.setSessionUsername("tester");
        appContext.setSessionCompany("test");
        appContext.saveSessionAttributes();
        return true;
    }

    public boolean validateApi(String username, String password) {
        boolean valid = false;

        //Creación de request
        UserLoginRequest requestObj = new UserLoginRequest(username, password);
        //Declaración de request
        Call<ResponseBody> call = client.userLogin(requestObj);
        JSONObject json = null;
        try {
            ResponseBody responseBody = call.execute().body();
            json = UtilsController.getJsonResponse(responseBody);
            boolean success = UtilsController.isJsonValid(json);
            String error = UtilsController.extractMessage(json);

            if (success) {
                User response = (User) UtilsController.extractDataJson(json, User.class);
                appContext.setSessionToken(response.getToken());
                appContext.setSessionUserType(response.getUserType());
                appContext.setSessionUsername(response.getUsername());
                appContext.setSessionCompany(response.getCompanyName());
                appContext.saveSessionAttributes();
                valid = true;
            } else {
                onLoginFailed(error);
                return false;
            }

        } catch (IOException e) {
            //Error en lectura de respuesta de servidor
            onLoginFailed("Error interno. Intente más tarde");
        } catch (JSONException e) {
            //Error en campos de respuesta
            onLoginFailed("Error interno. Intente más tarde");
        } catch (Exception e) {
            //Error general
            if (json == null) {
                onLoginFailed("Error interno. Intente más tarde");
            }
            onLoginFailed("Login failed");
        }
        return valid;
    }

    public void loadUserView(String userType) {
        if (userType != null && Constants.VENDOR.equals(userType)) {
            Intent userView = new Intent(this, VendorMain.class);
            startActivity(userView);
        } else if (Constants.COURIER.equals(userType)) {
            Intent userView = new Intent(this, CourierMain.class);
            startActivity(userView);
        }
    }

}

row_item.xml(下图)

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp">


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">

    </LinearLayout>

    <Button
        android:text="EDITAR"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:id="@+id/cancel_btn" />

    <Button
        android:text="Cancelar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edit_btn"
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@+id/cancel_btn"
        android:layout_toStartOf="@+id/cancel_btn"
        android:layout_marginRight="7dp"
        android:layout_marginEnd="7dp" />

    <TextView
        android:id="@+id/orden_title_text"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ORDEN #"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="@android:color/black"
        android:layout_alignBaseline="@+id/edit_btn"
        android:layout_alignBottom="@+id/edit_btn"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/textbox1"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="7dp"
        android:text=" "
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="@android:color/black"
        android:layout_alignBaseline="@+id/orden_title_text"
        android:layout_alignBottom="@+id/orden_title_text"
        android:layout_toRightOf="@+id/orden_title_text"
        android:layout_marginStart="7dp" />

</RelativeLayout>

row_item.xml "What i have so far"

如果需要其他文件以帮助我,请告诉我,我会将其上传。

非常感谢你们。

2 个答案:

答案 0 :(得分:0)

您可以创建一个扩展BaseAdapter的新类,并在getView方法中使用按钮完成所需的操作。在使用listView的活动中,您使用setAdapter。

答案 1 :(得分:0)

创建一个类似

的类
public class TestAdapter extends BaseAdapter {

    Context context;

    public TestAdapter(Context context)
    {
        this.context=context;
    }

    //count of number of items in listview may be depending on the array ua passing....here i am keeping 5 it may be according to you!
    int count=5;

    @Override
    public int getCount() {
        return 5;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        convertView= LayoutInflater.from(context).inflate(R.layout.row_item,parent,false);

        TextView ordentitle=(TextView)convertView.findViewById(R.id.orden_title_text);

        TextView textbox1=(TextView)convertView.findViewById(R.id.textbox1);


        ordentitle.setText("Whatever yout text is");

        textbox1.setText("whatever your text is");

        Button editar=(Button)convertView.findViewById(R.id.edit_btn);

        Button cancel=(Button)convertView.findViewById(R.id.cancel_btn);


        editar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //funtionality of edit button
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //functionality of cancel button
            }
        });


        return convertView;
    }
}

然后将此适配器设置为活动或片段中的listview,如下所示:

TestAdapter testAdapter=new TestAdapter(YourActivity.this)

yourlistview.setAdapter(testAdapter);
再来一个指针:

你编辑按钮ID为cancel_btn,取消按钮ID为edit_btn!