Android - 引用onDialogPositiveClick中的onListItemClick?

时间:2014-03-30 19:29:33

标签: android adt

是否可以在onDialogPositiveClick中引用onListItemClick?我可以在onDialogPositiveClick上放置onListItemClick,还是我必须做一些完全不同的事情?这是我的代码...感谢所有/任何帮助!

public class MainActivity extends ListActivity implements TheDialog.NoticeDialogListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);

    String[] sites = {"Google", "Amazon", "Ebay" , "Reddit", "SmashingMag", "CCC"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.mylist_item, R.id.textView1, sites);
    setListAdapter(adapter);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    DialogFragment newFragment = new TheDialog();
    newFragment.show(getFragmentManager(), "Confirm");
    Intent i = null;
    switch(position){
    case 0:
        i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
        startActivity(i); break;
    case 1:
        i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.amazon.com"));
        startActivity(i); break;
    case 2:
        i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.ebay.com"));
        startActivity(i); break;
    case 3:
        i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.reddit.com"));
        startActivity(i); break;
    case 4:
        i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.smashingmag.com"));
        startActivity(i); break;
    case 5:
        i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.myccc.corning-cc.edu"));
        startActivity(i); break;
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onDialogPositiveClick(DialogFragment dialog) {
    // TODO Auto-generated method stub
}

@Override
public void onDialogNegativeClick(DialogFragment dialog) {
    // TODO Auto-generated method stub

}

}

1 个答案:

答案 0 :(得分:0)

TheDialog完成后,您的对话框onListItemClick将仅显示,并根据您的switch逻辑处理选择。

因此,在解除对话后,您不需要再次调用它。我通常建议不要直接致电onListItemClick

此外,当您在Intent.ACTION_VIEW中使用onListItemClick启动活动时,您的对话框可能会被浏览器窗口隐藏,直到您返回到您的活动。

我想您只是希望在根据点击的列表项打开Url之前,您的对话框可以作为确认。您可以通过对代码进行简单更改来实现此目的:

  • 在活动中声明成员意图:Intent mActionViewIntent;

  • switch cases更改为:


case 0:
    mActionViewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
    break; // note not sending intent here
case 1:
    mActionViewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.amazon.com"));
    break; 

// ..etc
  • 如果用户使用对话框确认,则使用mActionViewIntent启动活动:


@Override
public void onDialogPositiveClick(DialogFragment dialog) {
    startActivity(mActionViewIntent); // start web-browser
}