android - onClickItem ListView 自定义 ArrayAdapter Android Studio

标签 android listview android-arrayadapter

下午好

我正在尝试从我的 listView 中触摸一个 listItem 并检测触摸(并获取哪个 listItem 被触摸),因为之后我将显示一个包含帖子信息的新 Activity。

但我遇到了问题,因为我不知道该怎么做,而且我尝试了很多不同的教程和代码,但在我的案例中它从来没有用过,这就是为什么我要发布我的完整代码因为我现在别无选择。

这是我的代码:

public class Blog extends AppCompatActivity {

// URL
String url = "https://www.mywebsite.com/";

// Key JSON
String keyJSON = "posts";

// Construct the data source
ArrayList<Blog> array = new ArrayList<Blog>();

// Background color action bar
String actionBarBackgroundColor = "#00b7bb";

// Title action bar
String actionBarTitle = "Blog";

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

    // Action Bar
    setupActionBar(actionBarBackgroundColor, actionBarTitle);

    // Create the adapter to convert the array to views
    final BlogAdapter adapter = new BlogAdapter(this, array);

    // Load posts
    initBlog(adapter);
}

// Action Bar
public void setupActionBar(String color, String titulo) {
    // Create Action bar
    ActionBar mActionBar = getSupportActionBar();

    // Display title
    getSupportActionBar().setTitle(titulo);

    // Action bar background
    mActionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(color)));

    // Show back arrow
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
}

// Get the information and display it in the ListView
private void initBlog(final BlogAdapter adapter) {

    // List View
    ListView listView = (ListView) findViewById(R.id.listv);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            Log.d("Click","Click");
        }
    });

    // Attach the adapter to a ListView
    listView.setAdapter(adapter);

    JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try{
                JSONObject jsonResponse = new JSONObject(response.toString());

                //Show result
                //Log.d("Result", jsonResponse.toString());

                JSONArray jsonMainNode = jsonResponse.optJSONArray(keyJSON);

                // Create products
                for(int i = 0; i<jsonMainNode.length();i++){
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                    String titulo = jsonChildNode.getString("title");
                    String fecha = jsonChildNode.getString("fecha");
                    String imagen = jsonChildNode.getString("imagen");
                    String introtext = jsonChildNode.getString("introtext");
                    String fulltext = jsonChildNode.getString("fulltext");

                    Blog newPost = new Blog(titulo, fecha, imagen, introtext, fulltext);

                    adapter.add(newPost);
                }
            }
            catch(JSONException e) {
                Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error", error.toString());
        }
    });

    // Access the RequestQueue through your singleton class.
    MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
}

// Back arrow action
public boolean onOptionsItemSelected(MenuItem item){
    Intent myIntent = new Intent(getApplicationContext(), MenuPrincipal.class);
    startActivityForResult(myIntent, 0);
    return true;
}
}

ListView :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="0dp"
tools:context=".Blog.Blog"
>
<ListView
    android:id="@+id/listv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10px">
</ListView>

列表项 View :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:layout_gravity="center_vertical|center_horizontal">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical|center_horizontal"
        android:gravity="right">

        <TextView
            android:id="@+id/blog_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="0dp"
            android:layout_marginBottom="0dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true"
            android:gravity="left"
            android:textColor="@color/colorBlack"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            android:textStyle="bold"
            android:padding="0px" />

        <TextView
            android:id="@+id/blog_fecha"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"
            android:layout_marginTop="0dp"
            android:textColor="@color/colorBlack"
            android:layout_marginBottom="0dp"
            android:textStyle="italic" />

        <ImageView
            android:id="@+id/blog_image"
            android:gravity="center_vertical|center_horizontal"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"
            android:layout_marginRight="0dp"
            android:layout_marginTop="0dp"
            android:layout_marginBottom="0dp"
            android:layout_width="match_parent"
            android:layout_height="350px" />

        <TextView
            android:id="@+id/blog_intro"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"
            android:layout_marginTop="0dp"
            android:layout_marginBottom="0dp"
            android:textColor="@color/colorBlack"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:lineSpacingExtra="4sp" />

        <Button
            android:text="Ver post"
            android:layout_width="wrap_content"
            android:id="@+id/button"
            android:textAppearance="@style/TextAppearance.AppCompat"
            android:background="@color/color"
            android:textColor="@color/blanco"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:paddingLeft="20px"
            android:paddingRight="20px"
            android:layout_marginTop="20px" />

    </LinearLayout>

</LinearLayout>

博客适配器:

public class BlogAdapter extends ArrayAdapter<Blog> {

public BlogAdapter(Context context, ArrayList<Blog> blogs) {
    super(context, 0, blogs);
}

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

    // Get the data item for this position
    Blog blog = getItem(position);

    // Check if an existing view is being reused, otherwise inflate the view
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.blog_item, parent, false);
    }


    TextView blogTitulo = (TextView) convertView.findViewById(R.id.blog_title);
    TextView blogFecha = (TextView) convertView.findViewById(R.id.blog_fecha);
    ImageView blogImagen = (ImageView) convertView.findViewById(R.id.blog_image);
    TextView blogIntrotext = (TextView) convertView.findViewById(R.id.blog_intro);

    blogTitulo.setText(blog.titulo);
    blogFecha.setText(blog.fecha);
    blogIntrotext.setText(blog.introtext);

    Picasso.with(getContext()).load(blog.imagen).into(blogImagen);

    return convertView;
}
}

提前致谢

问候

最佳答案

First of all make your class Parcelable or Serializable You need to add the ItemClickListener to your listview

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(Blog.this,ActivityToOpen.class);
                intent.putParcelable("BlogModeKey",array.get(position));
                startActivity(intent);
            }
        });

并在 ActivityToOpen 中读取该对象。

注意 或者使用 putExtra 一个一个地发送每个 Blog 模型属性

并且不要为模型类和 Activity 使用相同的名称

关于android - onClickItem ListView 自定义 ArrayAdapter Android Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40302266/

相关文章:

android - 新 Activity 无法使用 StartActivity Android studio 打开

android - ListView中的checkbox 'Checked'滚动后恢复

java - 如何从另一个类更改 imageview 源?

android - 如何在我的 fragment 和适配器中添加更多负载

Android - 何时将父 ViewGroup 传递给 LayoutInflater.inflate?

java - 自定义 ArrayAdapter 中未出现字体

java - 使用 SharedPreferences 在 ArrayAdapter 中存储和检索字符串

android - 如何在同一个页面加载WebView

java - Android 平板电脑和相机之间的 USB 批量传输

android - 从多选 ListView 返回值