Android将listview中的所选项目传递给popupMenu

时间:2016-04-21 17:40:24

标签: android listview popupmenu

我想传递所选项目" id"从listview到popupMenu,mainActivity:

public class ListChildrenActivity extends AppCompatActivity implements Config, PopupMenu.OnMenuItemClickListener {
private static final String TAG = "ListChildrenActivity";

ProgressDialog progressDialog;
Toolbar toolbar;
ChildrenAdapter adapter;
ListView listView;
int idConnexion, id;
private SwipeRefreshLayout refreshLayout;
Intent intent;
Child childObj;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_child);

    toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("Listes des enfants");
    toolbar.setNavigationIcon(R.drawable.back);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getBaseContext(), MainMedecinActivity.class);
            startActivity(intent);
        }
    });

    refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
    refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            showChildren();
        }
    });




    showChildren();

    listView = (ListView) findViewById(R.id.listview);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> myAdapter, View view, int itemInt, long lng) {
            //String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

            //Toast.makeText(ListChildrenActivity.this, selectedFromList, Toast.LENGTH_SHORT).show();
            //TextView v = (TextView)view.findViewById(R.id.tv);
            //String itemId = v.getText().toString();
            childObj = (Child) listView.getItemAtPosition(itemInt);
            id = childObj.getIdEnfant();
            Toast.makeText(ListChildrenActivity.this, ""+id, Toast.LENGTH_SHORT).show();


        }
    });
}

public void showMenu(View v) {
    PopupMenu popup = new PopupMenu(this, v);
    popup.setOnMenuItemClickListener(this);
    popup.inflate(R.menu.poupup_menu);
    popup.show();
}

private ArrayList<Child> generateData(String content) {
    ArrayList<Child> children = new ArrayList<Child>();
    JSONObject jObj = null;
    JSONArray ja = null;
    try {
        ja = new JSONArray(content);
        for (int i = 0; i < ja.length(); i++) {
            jObj = ja.getJSONObject(i);
            children.add(new Child(jObj.getInt("idEnfant"), jObj.getString("nomEnfant"), jObj.getString("prenomEnfant")));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return children;
}

public void showChildren() {

    if (!validate()) {
        failed();
        return;
    }

    SharedPreferences prefs = getSharedPreferences("Info_Connexion", Context.MODE_PRIVATE);
    idConnexion = prefs.getInt("idConnexion", 0);

    progressDialog = new ProgressDialog(ListChildrenActivity.this);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage("La liste des enfants ...");
    progressDialog.show();

    if (isOnline()) {
        requestData(SERVER_URL + "enfant/read/", idConnexion);
    } else {
        Toast.makeText(ListChildrenActivity.this, "Eroor network", Toast.LENGTH_SHORT).show();

    }
}

private void requestData(String url, int id) {
    DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    RequestPackage p = new RequestPackage();
    p.setMethod("POST");
    p.setUri(url);
    p.setParam("idMedecin", String.valueOf(id));

    MessagesTask task = new MessagesTask();
    task.execute(p);
}

protected boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

public void success(final int id, final ProgressDialog progressDialog, String content, SwipeRefreshLayout refreshLayout) {

    // 1. pass context and data to the custom adapter
    adapter = new ChildrenAdapter(this, generateData(content));

    // 2. Get ListView from activity_main.xml


    // 3. setListAdapter
    listView.setAdapter(adapter);
    if (id != 0) {
        refreshLayout.setRefreshing(false);
        progressDialog.dismiss();
    } else {
        refreshLayout.setRefreshing(false);
        progressDialog.dismiss();
        Toast.makeText(ListChildrenActivity.this, "Eroor server or input", Toast.LENGTH_SHORT).show();
    }


}

public boolean validate() {
    boolean valid = true;

    return valid;
}

public void failed() {
    Toast.makeText(getBaseContext(), "List Children failed", Toast.LENGTH_LONG).show();
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
       case android.R.id.home:
            onBackPressed();
            return true;

    }
    return super.onOptionsItemSelected(item);
}

@Override
public boolean onMenuItemClick(MenuItem item) {
    TextView scoreView = (TextView) findViewById(R.id.score);
    switch (item.getItemId()) {
        case R.id.infos:
            intent = new Intent(getBaseContext(), ChildInformationsActivity.class);
            intent.putExtra("idEnfant", id );
            startActivity(intent);
            return true;
        case R.id.signes_diagnostic:
            intent = new Intent(getBaseContext(), ChildSignesDiagnosticActivity.class);
            intent.putExtra("idEnfant", id);
            startActivity(intent);
            return true;
        case R.id.bilan_bio:
            intent = new Intent(getBaseContext(), ChildBilanBioActivity.class);
            intent.putExtra("idEnfant", id);
            startActivity(intent);
            return true;
        case R.id.traitement_medical:
            intent = new Intent(getBaseContext(), ChildTraitementMedicalActivity.class);
            intent.putExtra("idEnfant", id);
            startActivity(intent);
            return true;
        case R.id.imagerie:
            intent = new Intent(getBaseContext(), ChildImagerieActivity.class);
            intent.putExtra("idEnfant", id);
            startActivity(intent);
            return true;
        default:
            return false;
    }
}


private class MessagesTask extends AsyncTask<RequestPackage, String, String> {

    @Override
    protected String doInBackground(RequestPackage... params) {

        String content = HttpManager.getData(params[0]);

        return content;
    }

    @Override
    protected void onPreExecute() {
        System.out.println("onPreExecute");
    }

    @Override
    protected void onPostExecute(String content) {
        Log.i(TAG, "------------------------" + content);

        success(idConnexion, progressDialog, content, refreshLayout);

    }
}

}

enter image description here

类适配器:

public class ChildrenAdapter extends ArrayAdapter<Child> {

private final Context context;
private final ArrayList<Child> childrenArrayList;

public ChildrenAdapter(Context context, ArrayList<Child> childrenArrayList) {

    super(context, R.layout.row_child, childrenArrayList);

    this.context = context;
    this.childrenArrayList = childrenArrayList;
}

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

    // 1. Create inflater
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // 2. Get rowView from inflater
    View rowChildView = inflater.inflate(R.layout.row_child, parent, false);

    // 3. Get the two text view from the rowView
    TextView nameView = (TextView) rowChildView.findViewById(R.id.name);
    TextView dateView = (TextView) rowChildView.findViewById(R.id.date);
    TextView scoreView = (TextView) rowChildView.findViewById(R.id.score);
    // 4. Set the text for textView
    //String text = childrenArrayList.get(position).getNomEnfant())+" "+childrenArrayList.get(position).getNomEnfant();
    nameView.setText(childrenArrayList.get(position).getNomEnfant()+" "+childrenArrayList.get(position).getPrenomEnfant());
    dateView.setText("22/12/2012");
    scoreView.setText(String.valueOf(childrenArrayList.get(position).getIdEnfant()));
    scoreView.setBackgroundResource(R.drawable.circular_textview);

    // 5. retrn rowView
    return rowChildView;
}


}

当我点击列表视图的行时,我得到了&#34; id&#34;但我怎么能把它传递给popupMenu。

解决方案:它只是将settag(位置)添加到getview中的imageview,然后:

public void showMenu(View v) {
    PopupMenu popup = new PopupMenu(this, v);
    popup.setOnMenuItemClickListener(this);
    popup.inflate(R.menu.poupup_menu);
    popup.show();
    listView.performItemClick(v, (Integer) v.getTag(),listView.getItemIdAtPosition((Integer) v.getTag()));
}

2 个答案:

答案 0 :(得分:0)

您可以使用界面在它们之间进行通信

在适配器类中,初始化

private OnItemSelectedListener mListener;

并添加这些方法

  public void setOnItemClickLister(OnItemSelectedListener mListener) {
        this.mListener = mListener;
    }
//Creating an interface

    public interface OnItemSelectedListener {
        public void onItemSelected(String s);
    }

在适配器中的onClick函数

使用此

  mListener.onItemSelected(id);
//id is your string

您可以在MainActivity中调用它,

    adapter.setOnItemClickLister(new OnItemSelectedListener() {
               @Override
               public void onItemSelected(String s) {
//you will get the string here, you can pass it as an argument in popup menu


       }
         });

答案 1 :(得分:0)

在适配器端:

view.findViewById(R.id.menu_btn).setTag(id);

在ListActivity Side:

public void showPopUp(View v){
        currentId = v.getTag().toString();
        PopupMenu popupMenu=new PopupMenu(this,v);
        popupMenu.setOnMenuItemClickListener(ListActivity.this);
        MenuInflater inflater=popupMenu.getMenuInflater();
        inflater.inflate(R.menu.my_pop_up,popupMenu.getMenu());
        popupMenu.show();
    }

在XML方面:

<ImageButton android:id="@+id/menu_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_overflow"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="20dp"
            android:layout_alignParentEnd="true"
            android:layout_centerVertical="true"
            android:onClick="showPopUp"/>

注意:onClick =“showPopUp”在这里非常关键。 这应该会有所帮助。谢谢。