简体   繁体   English

如何为表格中的每个项目添加上下文菜单?

[英]How can I add a contextual menu for each item on a table?

I have a TableLayout that contains TextViews, and in each TextView I have a String with the name of a product. 我有一个包含TextViews的TableLayout,在每个TextView中都有一个带有产品名称的String。 I create the TextViews dynamically, depending on the length of the array of products I have in the database. 我根据数据库中产品阵列的长度动态创建TextView。 I want to add a contextual menu to allow the user to delete the product. 我想添加一个上下文菜单,以允许用户删除产品。 I tried this solution: http://www.sgoliver.net/blog/?p=1784 but it didn't work. 我尝试了以下解决方案: http : //www.sgoliver.net/blog/?p=1784,但是没有用。

public class FavoritesActivity extends Activity {

    AndroidHttpClient httpClient = HttpClientSingleton.getHttpClient();
    JSONArray productArrayList;
    String productId;
    String productDescription;
    String productBrand;

    public void onStartActivityDetailProduct(){
        Intent intent = new Intent(this, ProductActivity.class);
        intent.putExtra("productId", productId);
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favorites);
        try {
            getFavoriteItems();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        TableLayout table = (TableLayout) findViewById(R.id.tableOfFavorites); 
        registerForContextMenu(table);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
    {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_contextual_favorites, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.option_borrar:
                unsetAsFavorite();
            default:
                return super.onContextItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.favorites, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void getFavoriteItems() throws IOException{
        new Thread(){
            public void run(){
                //background code...
                try {
                    String username = UserDataSingleton.getUsername();
                    HttpGet httpget = new HttpGet("http://romal.hopto.org/foodadvisor/favorites/index.json?username="+username);
                    HttpResponse httpresp = httpClient.execute(httpget);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    httpresp.getEntity().writeTo(baos);
                    final String content = new String(baos.toByteArray());
                    FavoritesActivity.this.runOnUiThread(new Runnable(){
                        public void run(){
                            //foreground code (UI)
                            //update user interface, for example, showing messages
                            try {
                                JSONObject jObject = new JSONObject(content);
                                JSONArray productsList = jObject.getJSONArray("response");
                                productArrayList = productsList;
                                TextView[] textArray = new TextView[productsList.length()];
                                TableRow[] tr_head = new TableRow[productsList.length()];
                                TableLayout tl = (TableLayout) findViewById(R.id.tableOfFavorites);
                                for(int i=0; i<productsList.length();i++){
                                    JSONObject product = productsList.getJSONObject(i);
                                    JSONObject productData = product.getJSONObject("Product");
                                    productDescription = productData.getString("description");
                                    productBrand = productData.getString("brand");
                                    tr_head[i] = new TableRow(getApplicationContext());
                                    tr_head[i].setId(i+1);
                                    tr_head[i].setLayoutParams(new LayoutParams(
                                    LayoutParams.MATCH_PARENT,
                                    LayoutParams.WRAP_CONTENT));
                                    textArray[i] = new TextView(getApplicationContext());
                                    textArray[i].setId(i);
                                    textArray[i].setText(productDescription + " - " + productBrand);
                                    textArray[i].setPadding(40, 15, 40, 15);
                                    textArray[i].setTextSize(16);
                                    tr_head[i].addView(textArray[i]);
                                    tl.addView(tr_head[i], new TableLayout.LayoutParams(
                                             LayoutParams.MATCH_PARENT,
                                             LayoutParams.WRAP_CONTENT));
                                    textArray[i].setOnClickListener(new View.OnClickListener() 
                                    {                   
                                        @Override
                                        public void onClick(View v)
                                        {
                                            try {
                                                productId = productArrayList.getJSONObject(v.getId()).getJSONObject("Product").getString("id");
                                            } catch (JSONException e) {
                                                // TODO Auto-generated catch block
                                                e.printStackTrace();
                                            }
                                            onStartActivityDetailProduct();
                                        }
                                    });
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }   
                        }
                    });
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();  
    }


    public void unsetAsFavorite(){
        new Thread(){
            public void run(){
                //background code...
                try {
                    String productIdToDelete = productId;
                    HttpGet httpget = new HttpGet("http://romal.hopto.org/foodadvisor/favorites/unsetAsFavorite.json?id="+productIdToDelete);
                    HttpResponse httpresp = httpClient.execute(httpget);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    httpresp.getEntity().writeTo(baos);
                    final String content = new String(baos.toByteArray());

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

I don't know why it didn't work, but when I do a long press, the contextual menu doesn't appear. 我不知道为什么它不起作用,但是当我长按时,上下文菜单不会出现。 Thanks in advance :) 提前致谢 :)

You need to call registerForContextMenu() for each TableRow object. 您需要为每个TableRow对象调用registerForContextMenu()

And then add an OnLongClickListener to show the menu via view.showContextMenu() (this last part may not be necessary, but I think TableRow won't fire it otherwise). 然后添加一个OnLongClickListener以通过view.showContextMenu()显示菜单(这最后一部分可能没有必要,但我认为TableRow不会触发它)。

Aside #1: It looks like a ListView would be more suitable for this scenario than a TableLayout with dynamically added rows. 除了#1:与具有动态添加行的TableLayout相比, ListView似乎更适合这种情况。

Aside #2: Instead of a Thread + Runnable, you might want to consider AsyncTask (it's simpler). 除了#2:您可能要考虑使用AsyncTask (它更简单),而不是Thread + Runnable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM