问题
I am trying to move to other activity by clicking on list item which is loaded in list-view, but i don't why it is not moving to any other activity when i click on any list item nothing happens no crash, not moving to other activity nothing. Can any-one help me please.
I searched lot and got so many solution but any of the solution is not working in my case. Please help below is my activity code.
public class Classes_Ext_DB extends Activity implements OnClickListener {
ImageView imageViewNewClass, imageViewDelete;
ListView mListView;
/** Sliding Menu */
boolean alreadyShowing = false;
private int windowWidth;
private Animation animationClasses;
private RelativeLayout classesSlider;
LayoutInflater layoutInflaterClasses;
ArrayAdapter<CharSequence> adapterSpinner;
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_classDetail = "server detail/get_all_classdetail.php";
// url to delete product
private static final String url_delete_class = "server-detail/delete_class.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_ID = "ID";
private static final String TAG_CLASSNAME = "class_name";
// products JSONArray
JSONArray products = null;
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classes);
imageViewNewClass = (ImageView) findViewById(R.id.newclass);
imageViewDelete = (ImageView) findViewById(R.id.deletemenu);
mListView = (ListView) findViewById(R.id.displaydata);
productsList = new ArrayList<HashMap<String, String>>();
Display display = getWindowManager().getDefaultDisplay();
windowWidth = display.getWidth();
display.getHeight();
layoutInflaterClasses = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
Intent mIntent = new Intent(Classes_Ext_DB.this,
RecordAudio.class);
startActivity(mIntent);
}
});
new LoadAllClassDetail().execute();
imageViewNewClass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Classes_Ext_DB.this,
Class_Create_Ext_DB.class);
startActivityForResult(intent, 100);
}
});
imageViewDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Classes_Ext_DB.this);
final Spinner spinnerDelete = new Spinner(Classes_Ext_DB.this);
alertDialog.setView(spinnerDelete);
adapterSpinner = ArrayAdapter.createFromResource(
Classes_Ext_DB.this, R.array.delete_menu,
android.R.layout.simple_spinner_item);
adapterSpinner
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDelete.setAdapter(adapterSpinner);
alertDialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
if (spinnerDelete.getSelectedItemPosition() == 0) {
new DeleteProduct().execute();
}
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
alertDialog.show();
}
});
findViewById(R.id.skirrmenu).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!alreadyShowing) {
alreadyShowing = true;
openSlidingMenu();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100 then load item by reloading activity again
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllClassDetail extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Classes_Ext_DB.this);
pDialog.setMessage("Loading Classes. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_classDetail,
"GET", params);
// Check your log cat for JSON reponse
Log.d("All Classes: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String cid = c.getString(TAG_ID);
String cn = c.getString(TAG_CLASSNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, cid);
map.put(TAG_CLASSNAME, cn);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
Class_Create_Ext_DB.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} 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
* */
ListAdapter adapter = new SimpleAdapter(
Classes_Ext_DB.this, productsList,
R.layout.custom_class, new String[] {
TAG_CLASSNAME, TAG_ID },
new int[] { R.id.classname });
mListView.setAdapter(adapter);
mListView.setCacheColorHint(Color.TRANSPARENT);
}
});
}
}
/*****************************************************************
* Background Async Task to Delete Class
* */
class DeleteProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Classes_Ext_DB.this);
pDialog.setMessage("Deleting Class... Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ID", TAG_ID));
// getting product details by making HTTP request
JSONObject json = jParser.makeHttpRequest(url_delete_class,
"POST", params);
// check your log for json response
Log.d("Delete Product", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
private void openSlidingMenu() {
// showFadePopup();
int width = (int) (windowWidth * 0.8f);
translateView((float) (width));
@SuppressWarnings("deprecation")
int height = LayoutParams.FILL_PARENT;
// creating a popup
final View layout = layoutInflaterClasses.inflate(
R.layout.option_popup_layout,
(ViewGroup) findViewById(R.id.popup_element));
ImageView imageViewassignment = (ImageView) layout
.findViewById(R.id.assignment);
imageViewassignment.setOnClickListener(this);
ImageView imageViewfacebook = (ImageView) layout
.findViewById(R.id.likefb);
imageViewfacebook.setOnClickListener(this);
ImageView imageViewTwitter = (ImageView) layout
.findViewById(R.id.twitter);
imageViewTwitter.setOnClickListener(this);
ImageView imageViewBattery = (ImageView) layout
.findViewById(R.id.battery);
imageViewBattery.setOnClickListener(this);
ImageView imageViewAudio = (ImageView) layout.findViewById(R.id.audio);
imageViewAudio.setOnClickListener(this);
ImageView imageViewTakeNotes = (ImageView) layout
.findViewById(R.id.takenote);
imageViewTakeNotes.setOnClickListener(this);
ImageView imageViewAllNotes = (ImageView) layout
.findViewById(R.id.allnotes);
imageViewAllNotes.setOnClickListener(this);
ImageView imageViewReportBug = (ImageView) layout
.findViewById(R.id.reportbug);
imageViewReportBug.setOnClickListener(this);
ImageView imageViewFeedback = (ImageView) layout
.findViewById(R.id.feedback);
imageViewFeedback.setOnClickListener(this);
final PopupWindow optionsPopup = new PopupWindow(layout, width, height,
true);
optionsPopup.setBackgroundDrawable(new PaintDrawable());
optionsPopup.showAtLocation(layout, Gravity.NO_GRAVITY, 0, 0);
optionsPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
public void onDismiss() {
// to clear the previous animation transition in
cleanUp();
// move the view out
translateView(0);
// to clear the latest animation transition out
cleanUp();
// resetting the variable
alreadyShowing = false;
}
});
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.assignment:
Intent assign = new Intent(Classes_Ext_DB.this, Assignment.class);
startActivity(assign);
break;
case R.id.likefb:
Intent facebook = new Intent(Classes_Ext_DB.this,
FacebookLogin.class);
startActivity(facebook);
break;
case R.id.facebooklogin:
Intent twitter = new Intent(Classes_Ext_DB.this, TwitterLogin.class);
startActivity(twitter);
break;
case R.id.battery:
AlertDialog.Builder myDialogBattery = new AlertDialog.Builder(
Classes_Ext_DB.this);
myDialogBattery.setTitle("How to use Less Battery");
TextView textViewBattery = new TextView(Classes_Ext_DB.this);
ImageView imageViewBattery = new ImageView(Classes_Ext_DB.this);
imageViewBattery.setImageResource(R.drawable.batteryicon);
textViewBattery
.setText("The best way to use less amount of battery possible is to lower the brightness level on your device");
textViewBattery.setTextColor(Color.GRAY);
textViewBattery.setTextSize(20);
LayoutParams textViewLayoutParamsBattery = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
textViewBattery.setLayoutParams(textViewLayoutParamsBattery);
LinearLayout layoutBattery = new LinearLayout(Classes_Ext_DB.this);
layoutBattery.setOrientation(LinearLayout.VERTICAL);
layoutBattery.addView(textViewBattery);
layoutBattery.addView(imageViewBattery);
myDialogBattery.setView(layoutBattery);
myDialogBattery.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialogBattery.show();
break;
case R.id.audio:
AlertDialog.Builder myDialogAudio = new AlertDialog.Builder(
Classes_Ext_DB.this);
myDialogAudio.setTitle("How to get better audio notes");
TextView textViewAudio = new TextView(Classes_Ext_DB.this);
ImageView imageViewAudio = new ImageView(Classes_Ext_DB.this);
imageViewAudio.setImageResource(R.drawable.micicon);
textViewAudio
.setText("Getting the best sounding audio is important, to make sure you are getting the best audio notes possible always ensure that the microphone is facing the speakes.");
textViewAudio.setTextColor(Color.GRAY);
textViewAudio.setTextSize(20);
LayoutParams textViewLayoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
textViewAudio.setLayoutParams(textViewLayoutParams);
LinearLayout layoutAudio = new LinearLayout(Classes_Ext_DB.this);
layoutAudio.setOrientation(LinearLayout.VERTICAL);
layoutAudio.addView(textViewAudio);
layoutAudio.addView(imageViewAudio);
myDialogAudio.setView(layoutAudio);
myDialogAudio.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialogAudio.show();
break;
case R.id.takenote:
Intent takenote = new Intent(Classes_Ext_DB.this,
Classes_Ext_DB.class);
startActivity(takenote);
break;
case R.id.allnotes:
Intent allNotes = new Intent(Classes_Ext_DB.this, RecordAudio.class);
startActivity(allNotes);
break;
case R.id.reportbug:
Intent reportBug = new Intent(Classes_Ext_DB.this, ReportBug.class);
startActivity(reportBug);
break;
case R.id.feedback:
Intent feedback = new Intent(Classes_Ext_DB.this, Feedback.class);
startActivity(feedback);
break;
}
}
private void translateView(float right) {
animationClasses = new TranslateAnimation(0f, right, 0f, 0f);
animationClasses.setDuration(100);
animationClasses.setFillEnabled(true);
animationClasses.setFillAfter(true);
classesSlider = (RelativeLayout) findViewById(R.id.classes_slider);
classesSlider.startAnimation(animationClasses);
classesSlider.setVisibility(View.VISIBLE);
}
private void cleanUp() {
if (null != classesSlider) {
classesSlider.clearAnimation();
classesSlider = null;
}
if (null != animationClasses) {
animationClasses.cancel();
animationClasses = null;
}
}
}
Edit
MyXML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/classes_slider"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back_bg"
android:orientation="vertical" >
<ImageView
android:id="@+id/headerbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="@drawable/headerbar_small" />
<ImageView
android:id="@+id/skirrlogo"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:src="@drawable/skirrwhite" />
<ImageView
android:id="@+id/skirrmenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:src="@drawable/slideropener" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/skirrlogo"
android:layout_marginLeft="15dp"
android:layout_toRightOf="@+id/skirrlogo"
android:text="@string/classses"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold" />
<ImageView
android:id="@+id/newclass"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/headerbar"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:src="@drawable/class_button_new" />
<ImageView
android:id="@+id/deletemenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/skirrlogo"
android:src="@drawable/menubutton_large" />
<ListView
android:id="@+id/displaydata"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/newclass" >
</ListView>
</RelativeLayout>
custom_class.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/classname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:textStyle="bold" />
</LinearLayout>
回答1:
The issue is that Android doesn't allow you to select list items that have elements on them that are focusable. I modified the checkbox on the list item to have an attribute like so:
android:focusable="false"
android:focusableInTouchMode="false"
Now my list items that contain checkboxes (works for buttons too) are "selectable" in the traditional sense (they light up, you can click anywhere in the list item and the "onListItemClick" handler will fire, etc).
回答2:
Add android:focusable=false
in checkbox of custom_class.xml
回答3:
Add this
android:descendantFocusability="blocksDescendants
to the root element in custom_class.xml
Probably checkbox takes focus when you click on list item. So just add the above to the root element in xml.
http://developer.android.com/reference/android/view/ViewGroup.html#attr_android:descendantFocusability
android:descendantFocusability
Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.
Must be one of the following constant values.
Constant Value Description
beforeDescendants 0 The ViewGroup will get focus before any of its descendants.
afterDescendants 1 The ViewGroup will get focus only if none of its descendants want it.
blocksDescendants 2 The ViewGroup will block its descendants from receiving focus.
This corresponds to the global attribute resource symbol descendantFocusability.
You can also add
android:focusable= "false"
for the checkbox
android:focusable
Boolean that controls whether a view can take focus. By default the user can not move focus to a view; by setting this attribute to true the view is allowed to take focus. This value does not impact the behavior of directly calling requestFocus(), which will always request focus regardless of this view. It only impacts where focus navigation will try to move focus.
Must be a boolean value, either "true" or "false".
回答4:
Change
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
to
mListView.setOnItemClickListener(new OnItemClickListener()
回答5:
mListView.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
Intent mIntent = new Intent(Classes_Ext_DB.this,
RecordAudio.class);
startActivity(mIntent);
}
});
回答6:
Have you tried android:focusable="false" on the checkbox ?
来源:https://stackoverflow.com/questions/20967000/setonitemclicklistener-is-not-working-in-list-view-android