我无法使用波纹管代码访问项目的内容。为什么?我做错了什么?
那么我的问题可能是什么? 这是代码:
listView1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
{
AlertDialog.Builder adb = new AlertDialog.Builder(
MainActivity.this);
adb.setTitle("ListView OnClick");
RelativeLayout rl = (RelativeLayout) v.getParent();
TextView titlu = (TextView) rl.findViewById(R.id.txtTitle);
rl.findViewById(R.id.txtLocalitate);
adb.setMessage("Selected = "+ titlu.getText().toString());
adb.setPositiveButton("Ok", null);
adb.show();
}
});
如果我这样做
RelativeLayout rl = (RelativeLayout) arg0.getParent();
然后我没有收到点击错误,但AlertDialog中显示的值只显示第一个项目的值。所以这不是要走的路...... 如果我保留上面的代码,onItemClick我收到“强制关闭”的错误。错误日志可在下面找到:
07-30 18:36:09.903: W/dalvikvm(1304): threadid=1: thread exiting with uncaught exception (group=0x40015560)
07-30 18:36:09.914: E/AndroidRuntime(1304): FATAL EXCEPTION: main
07-30 18:36:09.914: E/AndroidRuntime(1304): java.lang.ClassCastException: android.widget.ListView
07-30 18:36:09.914: E/AndroidRuntime(1304): at softwarex.mycostomlistview.MainActivity$1.onItemClick(MainActivity.java:50)
07-30 18:36:09.914: E/AndroidRuntime(1304): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
07-30 18:36:09.914: E/AndroidRuntime(1304): at android.widget.ListView.performItemClick(ListView.java:3513)
07-30 18:36:09.914: E/AndroidRuntime(1304): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1812)
07-30 18:36:09.914: E/AndroidRuntime(1304): at android.os.Handler.handleCallback(Handler.java:587)
07-30 18:36:09.914: E/AndroidRuntime(1304): at android.os.Handler.dispatchMessage(Handler.java:92)
07-30 18:36:09.914: E/AndroidRuntime(1304): at android.os.Looper.loop(Looper.java:123)
07-30 18:36:09.914: E/AndroidRuntime(1304): at android.app.ActivityThread.main(ActivityThread.java:3683)
07-30 18:36:09.914: E/AndroidRuntime(1304): at java.lang.reflect.Method.invokeNative(Native Method)
07-30 18:36:09.914: E/AndroidRuntime(1304): at java.lang.reflect.Method.invoke(Method.java:507)
07-30 18:36:09.914: E/AndroidRuntime(1304): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-30 18:36:09.914: E/AndroidRuntime(1304): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-30 18:36:09.914: E/AndroidRuntime(1304): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
看起来问题就在这里:
RelativeLayout rl = (RelativeLayout) v.getParent();
假设您的列表项基于RelativeLayout
,那么v
您正在寻找的RelativeLayout,而不是其父级。试试这个:
RelativeLayout rl = (RelativeLayout) v;
*这假设它真的 是RelativeLayout
。如果您有混合/变化的列表项,请确保您有某种方式将它们分开,或者您将获得另一个ClassCastException
。
答案 1 :(得分:0)
您正在尝试将AdapterView(在本例中我假设是ListView)转换为RelativeLayout,因此抛出ClassCastException。 v是发生点击的视图,它是您必须用来获取TextView的视图。而不是
RelativeLayout rl = (RelativeLayout) v.getParent();
你应该使用
RelativeLayout rl = (RelativeLayout)v;