Designed by JQ3C273!
252 字
1 分钟
Android学习笔记——ListView&GripView事件监听、页面跳转和携带数据
ListView事件监听
ListView使用匿名内部类的方式完成选择单个选项时监听类的实例化操作
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//i 改成position即位置
}
});
点击第一行时,position的值是0
ListView 页面跳转
新建layout_listview_ product.xml,作为商品页面
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ImageView
android:id="@+id/iv_pro_pic"
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_marginTop="30dp"
android:layout_gravity="center_horizontal"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="20dp"
>
<TextView
android:id="@+id/tv_pro_des"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:textSize="30dp"
android:layout_marginTop="10dp"
android:text="TextView"
/>
<TextView
android:id="@+id/tv_pro_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/orange2"
android:textStyle="bold"
android:textSize="45dp"
android:layout_marginTop="5dp"
android:text="TextView"/>
</LinearLayout>
</androidx.appcompat.widget.LinearLayoutCompat>
初始化、变量
ImageView ivProduct;
TextView tvTitle,tvPrice;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
}
private void initView() {
setContentView(R.layout.layout_listview_product);
ivProduct = findViewById(R.id.iv_pro_pic);
tvTitle = findViewById(R.id.tv_pro_des);
tvPrice = findViewById(R.id.tv_pro_price);
}
使用Intent实现页面跳转
以key-value的形式传递数据
key:自定义密钥;value:要传的数据
Intent intent = new Intent(ListViewBuffActivity.this,ProductActivity.class);//以key——value的形式传递数据,key:自定义密钥;value:要传的数据
intent.putExtra("des",des[position]);
intent.putExtra("prices",prices[position]);
startActivity(intent);
intent.putExtra("img",images[position]);
ProductActivity接收数据
Intent intent = getIntent();
String _des = intent.getStringExtra("des");
String _price = intent.getStringExtra("prices");
int _img = intent.getIntExtra("img",0);
tvTitle.setText(_des);
tvPrice.setText(_price);
ivProduct.setImageResource(_img);
成品展示
Android学习笔记——ListView&GripView事件监听、页面跳转和携带数据
https://blog.ytmc.fun/posts/android学习笔记listviewgripview事件监听页面跳转和携带数据