在listview之后添加Drawer中的按钮

时间:2015-07-23 06:20:57

标签: android android-layout listview android-listview

我在我的应用程序中使用导航抽屉,其中包含一个ListView来显示一些数据。我使用android.support.v4.widget.DrawerLayout lib完成了这个。现在我想在ListView Contain下面添加一个按钮抽屉。怎么做?

我的.xml是...........................................

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#990033" >

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawerlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/menuContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/linearlayout_titlebar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="1dp"
            android:background="#ffffcc"
            android:orientation="horizontal" >

            <ImageButton
                android:id="@+id/imgbtnDrawer"
                android:layout_width="20dp"
                android:layout_height="35dp"
                android:layout_marginTop="6dp"
                android:background="@drawable/ic_menu"
                android:contentDescription="@string/vegetables" />

            <ImageButton
                android:id="@+id/imgbtnLabel"
                android:layout_width="25dp"
                android:layout_height="30dp"
                android:layout_marginLeft="6dp"
                android:layout_marginTop="9dp"
                android:background="@drawable/image2"
                android:contentDescription="@string/vegetables" />

            <TextView
                android:id="@+id/lblLabel"
                android:layout_width="225dp"
                android:layout_height="40dp"
                android:layout_marginLeft="6dp"
                android:layout_marginTop="6dp"
                android:text="@string/vegetables"
                android:textSize="22sp" />

            <ImageButton
                android:id="@+id/imgbtnCart"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="11dp"
                android:background="@drawable/imgcart"
                android:contentDescription="@string/vegetables" />
        </LinearLayout>

        <ListView 
            android:id="@+id/lstShowVege"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </ListView>
    </LinearLayout>

    <ListView
        android:id="@+id/lstDrawerIn"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:background="#990033" >
    </ListView>

    <ListView
        android:id="@+id/lstDrawerCart"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:background="#990033"
        android:layout_above="@+id/btnSend"
        android:layout_alignParentTop="true" >
    </ListView>

    <Button
        android:id="@+id/btnSend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="Buy"
        android:layout_alignParentBottom="true" />
</android.support.v4.widget.DrawerLayout>

/ ** ............................................ .................................................. .................................................. .................我需要在lstDrawerCart下面的按钮..........谁代表我的应用程序中的右抽屉.......但只需添加按钮的xml代码在这里不允许我在抽屉中表示按钮它只是作为MainActivity View。此外,我正在处理左和右抽屉,所以如果我需要在布局中包装它我怎么能这样做.......................... .................................................. .................................................. ........... * /

公共类VegetablesActivity扩展了Activity实现OnItemClickListener,OnClickListener {

ListView lstDrawerIn,lstDrawerCart,lstShowVege;
String[] strTrailShow;
ImageButton imgbtnDrawer,imgbtnCart;
Intent intent;
DrawerLayout drawerLayout;
MyAdapter myAdapter;
ArrayList<String> arr_stringDisplay=new ArrayList<String>();
DBHelper dbHelper;

// Progress Dialog
private ProgressDialog pDialog;
// products JSONArray
JSONArray message = null;
//JSONObject 
JSONObject json;
//JSONParser object
JSONParser jsonParser = new JSONParser();
//ArrayList to carry HashMap
ArrayList<HashMap<String, String>> productsList;
ArrayList<HashMap<String, String>> productsListcart;

// url to get all products list
private static String url= "http://10.0.2.2/grocery/get_all_vegetables.php";
private static String url_getCart= "http://10.0.2.2/grocery/get_all_cartprod.php";

// JSON Node names
private static final String TAG_MESSAGE = "message";
private static final String TAG_VEGETABLE_ID = "vegetable_id";
private static final String TAG_VEGETABLE_NAME = "vegetable_name";
private static final String TAG_VEGETABLE_PRICE = "vegetable_price";
private static final String TAG_VEGETABLE_IMAGE = "vegetable_image";
private static final String TAG_PRODUCT_ID = "product_id";
private static final String TAG_PRODUCT_NAME = "product_name";
private static final String TAG_PRODUCT_PRICE = "product_price";
private static final String TAG_PRODUCT_QUANTITY = "product_quantity";
private static final String TAG_PRODUCT_IMAGE = "product_image";

//Arranging data to pass to the custom drawer to set in listview
String[] strDrawerIn;
private int[] image={R.drawable.facebook,R.drawable.facebook,R.drawable.facebook,R.drawable.facebook,R.drawable.facebook,R.drawable.facebook};

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_vegetables);

    dbHelper=new DBHelper(getApplicationContext());
    drawerLayout=(DrawerLayout)findViewById(R.id.drawerlayout);
    lstDrawerIn=(ListView)findViewById(R.id.lstDrawerIn);
    lstDrawerCart=(ListView) findViewById(R.id.lstDrawerCart);
    lstShowVege=(ListView)findViewById(R.id.lstShowVege);
    strDrawerIn=getResources().getStringArray(R.array.strDrawerIn);
    strTrailShow=getResources().getStringArray(R.array.strTrailShow);
    imgbtnDrawer=(ImageButton) findViewById(R.id.imgbtnDrawer);
    imgbtnCart=(ImageButton)findViewById(R.id.imgbtnCart);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();
    productsListcart = new ArrayList<HashMap<String, String>>();

/*  initialising the String array variable from resources. 
  * calling custom adapter constructer by passing "Initialise string array","image array","textView which show design of one row","context".
  * Finally put listener on listviw on which this custom adapter seted.
*/  strDrawerIn=getResources().getStringArray(R.array.strDrawerIn);
    myAdapter=new MyAdapter(strDrawerIn,image,this);
    lstDrawerIn.setAdapter(myAdapter);      
    lstDrawerIn.setOnItemClickListener(this);   

    lstShowVege.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int arg2,
                long arg3) {
            Toast.makeText(getApplicationContext(), "VEGE", Toast.LENGTH_SHORT).show();
            Button btnAddCart=(Button)findViewById(R.id.btnAddToCart);
            btnAddCart.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Toast.makeText(getApplicationContext(), "Button VEGE", Toast.LENGTH_SHORT).show();

                }
            });

        }
    });

    //Using onclickListener on imgbuttons
    imgbtnDrawer.setOnClickListener(this);
    imgbtnCart.setOnClickListener(this);

    checkconnection();

}//OnCreate close

private void refresh() {
    new LoadAllProducts().execute();
}

private void refreshCart() {
    new LoadCart().execute();
}

//Dialog to check Connection    
public void checkconnection()
{
    //checking connection of internet
    ConnectivityManager cManager = (ConnectivityManager) getSystemService(HomeActivity.CONNECTIVITY_SERVICE);
    NetworkInfo nInfo = cManager.getActiveNetworkInfo();

    if(nInfo!= null && nInfo.isConnected() ){
        //if connection present call background class
        refresh();
    }
    else{
        AlertDialog.Builder builder1 = new AlertDialog.Builder(VegetablesActivity.this);
        builder1.setCancelable(false);

        LayoutInflater inflator = getLayoutInflater();
        builder1.setView(inflator.inflate(R.layout.dialog_checkconnection, null));

        builder1.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        AlertDialog alert = builder1.create();
        alert.show();
    }
}

//coming here when clicked on ListView of Drawer that is, lstDrawerIn.
public void onItemClick(AdapterView<?> arg0, View v, int pos, long id) {
        selectitem(pos);
        switch (pos) {
        case 0:
            intent=new Intent(getApplicationContext(), HomeActivity.class);
            startActivity(intent);
            finish();
            break;

        case 1:
            intent=new Intent(getApplicationContext(), VegetablesActivity.class);
            startActivity(intent);
            finish();
            break;

         case 2:
            intent=new Intent(getApplicationContext(), FruitsActivity.class);
            startActivity(intent);
            finish();
            break;

         case 3:
            intent=new Intent(getApplicationContext(), DairyProductsActivity.class);
            startActivity(intent);
            finish();
            break;

         case 4:
            intent=new Intent(getApplicationContext(), AllActivity.class);
            startActivity(intent);
            finish();
            break;  

          default:
            break;
        }
 }
 //using to highlist the the selected item or textView From ListView of Drawer.
 public void selectitem(int pos) {
     lstDrawerIn.setItemChecked(pos, true);
 }

 @Override
 public void onClick(View v) {
     switch (v.getId()) {
        case R.id.imgbtnDrawer:
            if(drawerLayout.isDrawerOpen(lstDrawerIn))
            {
                drawerLayout.closeDrawer(lstDrawerIn);
            }
            else
            {
                drawerLayout.openDrawer(lstDrawerIn);
            }
            break;

        case R.id.imgbtnCart:
            if(drawerLayout.isDrawerOpen(R.id.lstDrawerCart))
            {
                drawerLayout.closeDrawer(lstDrawerCart);
            }
            else
            {
                drawerLayout.openDrawer(lstDrawerCart);
                refreshCart();
            }
            break;  

        default:
            break;
     }
 }

 /**
  * Background Async Task to Load all product by making HTTP Request
 **/
    class LoadAllProducts extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(VegetablesActivity.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting string array containg output at each position from JSONParser.
         String[] st = jsonParser.makeHttpRequest(url,"GET", params);

         for (int j = 0; j < st.length; j++) {
            try {
                    //Converting Strings of each position of st into the JSONObject.
                    json = new JSONObject(st[j]);

                    if (!json.equals(null)) {
                        // products found
                        // Getting Array of Products
                        message =  json.getJSONArray(TAG_MESSAGE);

                        // looping through All Products
                        for (int i = 0; i < message.length(); i++) {
                            JSONObject c = message.getJSONObject(i);

                            // Storing each json item in variable
                            String vegetable_id = c.getString(TAG_VEGETABLE_ID);
                            String vegetable_name = c.getString(TAG_VEGETABLE_NAME);
                            String vegetable_price = c.getString(TAG_VEGETABLE_PRICE);
                            String vegetable_image = c.getString(TAG_VEGETABLE_IMAGE);

                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            map.put(TAG_VEGETABLE_ID, vegetable_id);
                            map.put(TAG_VEGETABLE_NAME, vegetable_name);
                            map.put(TAG_VEGETABLE_PRICE, vegetable_price);
                            map.put(TAG_VEGETABLE_IMAGE, vegetable_image);

                            // adding HashList to ArrayList
                            productsList.add(map);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
         } 
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
      protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView using custom Adapter
                 * */
                BackgroundAdapter adapter = new BackgroundAdapter(VegetablesActivity.this, productsList, TAG_VEGETABLE_NAME, TAG_VEGETABLE_PRICE, TAG_VEGETABLE_IMAGE);
                // updating listview
                lstShowVege.setAdapter(adapter);
            }
        });
      }
}//background class close

/**
  * Background Async Task to Load all product by making HTTP Request
 **/
class LoadCart extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(VegetablesActivity.this);
        pDialog.setMessage("Loading Cart. Please wait...");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        productsListcart.clear();
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting string array containg output at each position from JSONParser.
         String[] st = jsonParser.makeHttpRequest(url_getCart,"GET", params);

        for (int j = 0; j < st.length; j++) {
            try {
                    //Converting Strings of each position of st into the JSONObject.
                    json = new JSONObject(st[j]);

                    if (!json.equals(null)) {
                        // products found
                        // Getting Array of Products
                        message =  json.getJSONArray(TAG_MESSAGE);

                        // looping through All Products
                        for (int i = 0; i < message.length(); i++) {
                                JSONObject c = message.getJSONObject(i);

                                // Storing each json item in variable
                                String product_id = c.getString(TAG_PRODUCT_ID);
                                String product_name = c.getString(TAG_PRODUCT_NAME);
                                String product_price = c.getString(TAG_PRODUCT_PRICE);
                                String product_quantity = c.getString(TAG_PRODUCT_QUANTITY);
                                String product_image = c.getString(TAG_PRODUCT_IMAGE);

                                // creating new HashMap
                                HashMap<String, String> map = new HashMap<String, String>();

                                // adding each child node to HashMap key => value
                                map.put(TAG_PRODUCT_NAME, product_name);
                                map.put(TAG_PRODUCT_PRICE, product_price);
                                map.put(TAG_PRODUCT_QUANTITY, product_quantity);
                                map.put(TAG_PRODUCT_IMAGE, product_image);

                                // adding HashList to ArrayList
                                productsListcart.add(map);
                            }
                        }
                    } catch (JSONException e) {
                    }
             } 
            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
          protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView using custom Adapter
                     * */
                    CartAdapter adapter = new CartAdapter(VegetablesActivity.this, productsListcart, TAG_PRODUCT_NAME, TAG_PRODUCT_PRICE, TAG_PRODUCT_QUANTITY, TAG_PRODUCT_IMAGE);
                    // updating listview
                    lstDrawerCart.setAdapter(adapter);
                    }
            });
          }
    }//background LOADCART class close
}//main class close

1 个答案:

答案 0 :(得分:0)

android.support.v4.widget.DrawerLayout采用两个视图,第一个是主内容视图,第二个是抽屉幻灯片上绘制的视图。

所以我建议在布局中包装除主要内容之外的所有视图,并将其放在主要内容布局下。

编辑:

据我所知,您想在右侧抽屉的列表视图下添加一个按钮,因此您应该使用线性布局中的按钮包装列表视图,并且不要忘记将它的重力设置为右侧