android自定义dialog中点击listview的item事件关闭dialog

分享到:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;


public class MainActivity extends Activity {


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


public void onClick(View v) {
View view = View.inflate(this, R.layout.layout_listview, null);
ListView lv = (ListView) view.findViewById(R.id.lv);
lv.setAdapter(new MyAdapter());
AlertDialog.Builder builder = new Builder(this);
final AlertDialog dialog = builder.setIcon(R.drawable.ic_launcher).setTitle("测试")
.setView(view).setPositiveButton("关闭", new DialogInterface.OnClickListener(){


@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub

}

}).show();

WindowManager manager = getWindowManager(); 
Display display = manager.getDefaultDisplay(); 
int width = display.getWidth(); 
int height = display.getHeight();
dialog.getWindow().setGravity(Gravity.BOTTOM |Gravity.LEFT);
dialog.getWindow().setLayout(width/2, height/4); 
lv.setOnItemClickListener(new OnItemClickListener() {


@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


dialog.dismiss();
Toast.makeText(MainActivity.this, "对话框消失了", Toast.LENGTH_SHORT).show();
}
});
}


private class MyAdapter extends BaseAdapter {


@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) {
return View.inflate(MainActivity.this, R.layout.layout_item, null);


}


}
}
昵    称:
验证码:

相关文档: